I want to use a struct pointer as a @property but I’m not sure how should I free it.
This is what I have now:
.h:
@property (nonatomic, assign) InfoStruct * info;
.m:
@synthesize info;
- (id)init {
self = [super init];
if (self) {
self.info = (struct InfoStruct *) malloc(sizeof(struct InfoStruct));
}
return self;
}
-(void)dealloc {
free(info);
[super dealloc];
}
Could the code above cause any trouble? Is it correct? Seems to work fine, but I think I need a reassurance.
It depends on how you use instances of that class. For example:
will be okay.
However, since you’ve declared that property to be read-write, you need to take into account the ownership of the object pointed by that structure.
For example, in:
the object you’ve allocated in
-initdoesn’t get freed (you’re leaking it), and the object pointed to bysomeInfogets freed. You could change the property setter to something like:in which case an assignment will always free the previous object unless the value being assigned is the same as the previous value. This means that your class effectively owns the object whose address is being assigned to the property.
If you decide that the class shouldn’t be responsible for freeing objects other than the one created in
-init, things get a tad more complicated. Ifinfois assigned some address other than the address of the originalinfocreated in-init, the client code needs to freeobj.infobefore assigning it a new value. For example:That’s problematic because you have code outside of the class deallocating memory used by an object of that class, which is quite intrusive. And, if the class isn’t responsible for freeing objects other than the one created in
-init, you need to keep additional state indicating that so that-dealloconly freesinfoifinfowasn’t changed after the object was initialised.Also, as Jim noted, the correct method name is
dealloc.