Memory management when returning an Objective-C object

In Objective-C, if I have a method in which I select and initialize an object and then return it, where / how to free it?

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

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

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

When can I let this object go? Or am I just auto-advertising?

+3
source share
3 answers
- (void)aMethod {
    UIView *aView = [self createObject];
}

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

The rules for managing memory are clear on this. You must read them. Very simple and fundamental to write Objective-C code using Apple frameworks.

+8
source

Remember also that the Garbage Collection is not present on the iPhone, so you cannot authorize if you are developing for this environment.

As for when you should free an object, the simple answer is when you finish using it and before you destroy your application.

-6
source

Source: https://habr.com/ru/post/1753634/


All Articles