Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a struct pointer as a @property

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.

like image 240
Rad'Val Avatar asked Jul 14 '26 00:07

Rad'Val


1 Answers

It depends on how you use instances of that class. For example:

SomeClass *obj = [SomeClass new];
// never assign an address to obj.info
[obj release];

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:

SomeClass *obj = [SomeClass new];
obj.info = someInfo;
[obj release];

the object you’ve allocated in -init doesn’t get freed (you’re leaking it), and the object pointed to by someInfo gets freed. You could change the property setter to something like:

- (void)setInfo:(InfoStruct *)newInfo {
    if (newInfo != info) {
        free(info); // free previous object
        info = newInfo;
    }
}

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. If info is assigned some address other than the address of the original info created in -init, the client code needs to free obj.info before assigning it a new value. For example:

SomeClass *obj = [SomeClass new];
free(obj.info);
obj.info = someInfo;
[obj release];

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 -dealloc only frees info if info wasn’t changed after the object was initialised.

Also, as Jim noted, the correct method name is dealloc.