Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C memory management--best practices when returning objects?

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.

like image 296
Sam Lee Avatar asked Mar 28 '09 03:03

Sam Lee


1 Answers

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.

like image 98
Travis Jensen Avatar answered Oct 06 '22 00:10

Travis Jensen