views:

85

answers:

4

In Objective-C, if I have a method in which I allocate and initialize an object, then return it, where/how do I release it?

for example, let's say I have a method where I create an object:

- (void)aMethod {
    UIView *aView = [self createObject];
}

- (UIView *)createObject {
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    return returnView;
}

When do I release this object? Or would I just autorelease it?

+7  A: 

The rules for memory management are clear on this matter. You should read them. Very simple, and fundamental for writing Objective-C code using Apple's frameworks.

jer
A: 

Remember also that Garbage Collection is not present on an iPhone so you can't autorelease if you are developing for that environment.

As to when you should release the object, the simple answer is when you are finished using it and before you destroy your application.

Chris Shelley
So in relation to my example above, would I release the object after I'm done with it in the `aMethod` method?
Calvin L
Garbage collection is available on iOS 4.0 and higher. Also, autorelease operates independent of garbage collection in non-gc environments. Solid downvote for that reason.
jer
@jer I'm almost certain that garbage collection isn't in any iOS
cobbal
@cobbal, http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CoreDataUtilityTutorial/Articles/02_creatingProj.html
jer
@jer from that link: "Platform: Mac OS X" a lot of mac stuff slips through into the iPhone docs
cobbal
-1 autorelease is *for* the non garbage collected environment. Of course you can use it there. In fact, in GC, it's effectively a no-op.
JeremyP
**There's no garbage collection on iOS.**
Nikolai Ruhe
+2  A: 
- (void)aMethod {
    UIView *aView = [self createObject];
}

- (UIView *)createObject {
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    [returnView autorelease];
    return returnView;
}
Kurbz
A: 

You may consider taking a look at Xcode's companion tool Accessorizer

Kevin Callahan