Suppose I have a function like this:
- (NSSet *) someFunction {
//code...
return [[[NSSet alloc] initWithObjets:obj1, obj2, nil] autorelease];
}
When I call this function, do I need to do retain/release the return value? I'm assuming I do.
However, what if I don't do autorelease, so someFunction now looks like this:
- (NSSet *) someFunction {
//code...
return [[NSSet alloc] initWithObjets:obj1, obj2, nil];
}
In this case, I'm assuming I need to release but not retain the return value.
My question is, what is the suggested/best practice for these kinds of situations? Is one or the other version of someFunction recommended? Thanks.
You should spend some time reading the Memory Management Programming Guide for Cocoa.
The short is that if you get your reference through a method starts with 'alloc' or 'new' or contains 'copy', you own the reference and do not have to retain it. You do have provide for its release, either through a direct release or through using autorelease.
If you get a reference any other way (through a class method or what-have-you), you do not own a reference, so you don't have to release. If you want to keep a reference, you have to retain it.
Over-all, it is really quite simple and effective.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With