3

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?

Calvin
  • 8,697
  • 7
  • 43
  • 51
  • possible duplicate of [memory management objective c - returning objects from methods](http://stackoverflow.com/questions/2742397/memory-management-objective-c-returning-objects-from-methods) – apaderno Aug 05 '10 at 18:12

3 Answers3

8

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
  • 20,094
  • 5
  • 45
  • 69
2
- (void)aMethod {
    UIView *aView = [self createObject];
}

- (UIView *)createObject {
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    [returnView autorelease];
    return returnView;
}
Kurbz
  • 11,003
  • 2
  • 17
  • 12
-6

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.

  • So in relation to my example above, would I release the object after I'm done with it in the `aMethod` method? – Calvin Jul 08 '10 at 03:05
  • 1
    @jer I'm almost certain that garbage collection isn't in any iOS – cobbal Jul 08 '10 at 03:15
  • @cobbal, http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CoreDataUtilityTutorial/Articles/02_creatingProj.html – jer Jul 08 '10 at 03:21
  • 2
    @jer from that link: "Platform: Mac OS X" a lot of mac stuff slips through into the iPhone docs – cobbal Jul 08 '10 at 03:46
  • -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 Jul 08 '10 at 07:34
  • 1
    **There's no garbage collection on iOS.** – Nikolai Ruhe Jul 11 '10 at 18:54