Keep / Free Returned Objects

I'm new to Objective-C, so this might be a dumb question.

I cannot help but see the similarities between ObjC and Microsoft COM regarding memory management ( AddRef/ Releasevs retain/ Release). In the COM environment, this more or less imposes on you always AddRef( retain) the object before returning it to the caller. From what I have seen so far (I'm third through Cocoa ® Programming for Mac® OS X (3rd edition) ), the memory management part is somewhat fuzzy.

Assuming there is no GC, what is the idiomatic way to return an object?

+5
source share
5 answers

.

Objective-C, , autoreleased ( , , , "alloc", "new", "copy" "mutableCopy" ). Objective-C , , . COM, release . , , , , alloc, new, copy mutableCopy, . .

+11

Cocoa AddRef/Release COM, ; autorelease.

  • retain - , .
  • Release - , .
  • autorelease - , , - .

: . , .

, (, , ARC):

  • , :
    • alloc
    • copy
    • new
    • retain
  • .

, :

-(NSString*)newHelloWorldString {
    NSString* s = [NSString stringWithString:@"Hello world"];
    // Apply retain because s in now autoreleased
    return [s retain];
}

-(NSString*)helloWorldString {
    NSString* s = [[NSString alloc] initWithString:@"Hello world"];
    // Apply autorelease because s is now retained.
    return [s autorelease];
}

-(NSString*)fullName {
    // No memory management needed, everything is autoreleased and good.
    NSString* fn = [self firstName];
    NSString* ln = [self lastName];
    NSString* s = [NSString stringWithFormat:@"%@ %@", fn, ln];
    return s;
}
+4

-

return [object autorelease];

.

Lion/iOS5 SDK, ARC.

+1

, , , . i.e stackoverflow .

i.e

-(void) setAnswer:(Answer*) _answer{
    self.answer = _answer; // If the answer is created from a returned message.
    [_answer release];
}

edit: , , , , . - :

Answer *_answer = [stackoverflow createAnswer];
self.answer = _answer;
[_answer release];
-1

If you return the object, the owner should save it, I would avoid auto-implementations where possible, because as soon as nspool exits, these objects will disappear, and if they are still in use, this will cause problems.

ie Answer * answer = [stackoverflow getAnswer], and if the answer was created in the getanswer method, then someone retrieves it, it is responsible for releasing it.

Has the meaning?

-3
source

All Articles