Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is releasing memory of Objective-c 2.0 properties required?

Something I have been wondering about properties for a while. When you are using properties, do you need to override the release message to ensure the properties are released properties?

i.e. is the following (fictitious) example sufficient?

@interface MyList : NSObject {
NSString* operation;
NSString* link;
}
@property (retain) NSString* operation;
@property (retain) NSString* link;
@end

@implementation MyList
@synthesize operation,link;
@end
like image 473
Jay Avatar asked Sep 07 '09 12:09

Jay


People also ask

What method is automatically called to release objects in Objective C?

The NSArray class method array returns a newly initialized array that is already set for autorelease. The object can be used throughout the method, and its release is handled when the autorelease pool drains. At the end of this method, the autoreleased array can return to the general memory pool.

How retain object in Objective C?

The system that Objective-C uses is called retain/release. The basic premise behind the system is that if you want to hold on to a reference to another object, you need to issue a retain on that object. When you no longer have a use for it, you release it. Similar to Java, each object has a retain count.


2 Answers

You should always release the backing variables in dealloc:

- (void) dealloc {
   [operation release];
   [link release];

   [super dealloc];
}

Another way:

- (void) dealloc {
   self.operation = nil;
   self.link = nil;

   [super dealloc];
}

That's not the preferred way of releasing the objects, but in case you're using synthesized backing variables, it's the only way to do it.

NOTE: to make it clear why this works, let's look at the synthesized implementation of the setter for link property, and what happens when it is set to nil:

- (void) setLink:(MyClass *) value {
   [value retain]; // calls [nil retain], which does nothing
   [link release]; // releases the backing variable (ivar)
   link = value;   // sets the backing variable (ivar) to nil
}

So the net effect is that it will release the ivar.

like image 167
Philippe Leybaert Avatar answered Oct 08 '22 20:10

Philippe Leybaert


In non-GC applications, yes. It is usual to assign nil instead of releasing the ivars. My best experience is to release ivars initialized with init and assign nil to properties with retain and copy mode.

In your case I would assign nil

- (void) dealloc {
   self.operation = nil;
   self.link = nil;
   [super dealloc];
}
like image 22
cocoafan Avatar answered Oct 08 '22 21:10

cocoafan