开发者

Objective-c Async memory management

I've had a look around but have been unable to find a definitive answer to this question.

If I have a class that performs an async operation,开发者_如何学Go when and how do I release it?

-(void)main 
{
     AsyncObject *async = [[AsyncObject alloc] initWithDelegate:self];

     [async goDoSomething];
}

-(void)didSomething:(Result*)result 
{   

}

When do I release *async?


You could keep a private property to save the value, or, if you have control over the AsyncObject, pass the instance in the didSomething: selector. I think the first option is better since you know the object will be retained until you get your delegate call.

Option 1:

ClassName.m

@interface ClassName ()
    @property (nonatomic, retain) AsyncObject* async;
@end

@interface
//...

-(void)main 
{
 async = [[AsyncObject alloc] initWithDelegate:self];

 [async goDoSomething];
}

-(void)didSomething:(Result*)result 
{   
    [async release];
    async = nil;
}

Option 2:

-(void)aysncObject:(AsyncObject*)async didSomething:(Result*)result {
    [async release];
}


If your object runs its asynchronous task on a background thread, or is the target of a timer, or uses GCD and is referenced within the scope of the dispatched block (the ^ {} kerjigger) then it will be retained for you for the lifetime of that background operation.

So the normal use case would be:

 AsyncObject *async = [[AsyncObject alloc] initWithDelegate:self];
 [async goDoSomething];
 [async release];

Now, it's possible to work in the background with an object that is not retained (e.g. by using a __block-scoped reference to the object with GCD, or by detaching your worker thread with pthreads instead of NSThread/NSOperation) but there are no typical use cases I can think of offhand where that would happen. In such a case, you should ensure that -goDoSomething internally retains and releases self for the duration of the operation.

(If somebody can think of a case where the object is not retained for you, please post in the comments and I'll update my answer.)


Thanks for the help guys, I did a bit of experimenting with NSURLConnection to see how it handled it (As you autorelease that and it will continue on with it's async operations).

Turns out at the beginning of every async step it internally bumps its retain count and at the end of every async step it internally releases itself.

This means that it can be sent autorelease/release and it won't actually be release until it has completed it's current operation.

// MAIN.M

-(void)main 
{
     AsyncObject *async = [[[AsyncObject alloc] initWithDelegate:self] autorelease];

     [async goDoSomething];
}

-(void)didSomething:(Result*)result 
{   

}

// ASYNCOBJECT.M

-(void) goDoSomething
{
   [self retain];
}

-(void) finishedDoingSomething
{
   [delegate didSomething:result];
   [self release]
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜