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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

-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.

6 Comments

So in relation to my example above, would I release the object after I'm done with it in the aMethod method?
@jer I'm almost certain that garbage collection isn't in any iOS
@jer from that link: "Platform: Mac OS X" a lot of mac stuff slips through into the iPhone docs
There's no garbage collection on iOS.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.