Objective-C returns alloc'd memory to == bad?

This is on the iPhone.

So if I have a function like

- (SomeObject*)buildObject;

Do I need to pass a variable that I have already selected outside, for example

- (void)assignObject(SomeObject** out);

Or can I do

- (SomeObject*)buildObject
{
   return [[[SomeObject alloc] init] autorelease];
}

and use it like

SomeObject* obj = [[otherObject buildObject] retain];

I would like to do the latter, but as far as I read it is undefined because autorelease only guarantees the object to the end of the function?

+3
source share
5 answers

In Objective-C, a memory management contract is as follows: everyone that calls alloc is responsible for invoking release. If the build function calls [[[Class Distribution] init] release], then the object is quickly created and destroyed.

, autorelease :

return [[[Class alloc] init] autorelease];

, , - , . - , .

:

- (SomeClass*) buildObject {
   return [[[SomeClass alloc] init] autorelease];
}

- (void) doSomething {
   c = [self buildObject];
   // Call [c retain] if you want c to stay around after the current run
   // loop is finished and clean it up later, e.g. in your delloc method.
}
+6

- , Cocoa; .

, , init, , , , .
, , .

:

- (id) initMyObject
{
    self = [super init];
    if (self) {
        // do something
    }
    return self
}

➔ , .

- (MyObject *) myObject
{
    return [[[MyObject alloc] initMyObject] autorelease];
}

➔ - , , , , , ( , ).

+4

/ NSAutoreleasePool.

( ), .

+1

, . Autorelease , . , ( + NSAutoreleasePool ), , . ; :

( ), , , .

, , , , .

+1
source

You can use the latter. I use this style in each of my applications and have never had a problem. The abstract will last for many, many, many execution cycles, much longer than the end of the function.

0
source

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


All Articles