Reputation: 12979
I know there are several "similar" questions out there, but I think this is an issue a lot of programmers have issues with and needs extra attention.
Say I have a factory method for a class that returns an autoreleased object:
+(id)queueWithDelegate:(id)aDelegate {
return [[[self alloc] initWithDelegate:aDelegate] autorelease];
}
When I call this function and receive my queue
object, must I explicitly retain
it, or does the simple fact that I am assigning it to a variable do it?
MyQueue q = [MyQueue queueWithDelegate:self]; // Does this need to be retained?
Or am I confusing this with properties? If I have a property like so:
@property (nonatomic, *retain*) myQueue;
// Does the "retain" part of the property mean it's going to automatically add
// to the retain count?
self.myQueue = [MyQueue queueWithDelegate:self]; // Do I need to call retain?
I think my issue may be that I've gotten properties mixed up with local variables. Thanks for any insight.
Upvotes: 0
Views: 92
Reputation: 57179
Yes the retain part of the property does mean that it will automatically retain the property but only when you use the property.
//self.xxxx is how you use the property and if retain is set it it will retain your queue
//likewise if copy were set it would copy the queue if possible
self.myQueue = [MyQueue queueWithDelegate:self];
Dong the following
MyQueue q = [MyQueue queueWithDelegate:self];
will not retain your queue automatically since an autoreleased object is expected to be returned by queueWithDelegate:
. The queue at this point is in the autorelease pool and will be valid within the function called as it is expected to be cleaned up no later than the beginning of the next run loop.
The Memory Management Programming Guide provides insight into when to expect an autoreleased object, when to retain, and when to release.
Upvotes: 3