开发者

When to release a variable in objective-c

I have the following line in my view controller:

-(void) retrieveAccounts {
    accounts = [[NSMutableArray alloc] init];
    selAccounts=[[NSMutableArray alloc] init];
    NSString *url=[NSString stringWithFormat:@"https://host/accts"];
    processor=[[AsynConnectionProcessorController alloc] init];
    processor.delegate=self;
    processor.server=self.server;
    [processor createRequestfromURL:url];
}

The AsynConnectionProcessorController class creates an NSURLConnection to load data from a url in asynchronous mode. It creates a connection in the createRequestfromURL method. Later when page is received comepltely in connectionDidFinishLoading I invoke a processData method on the delegate I set in above s开发者_如何转开发nippet. processData updates the tableView and so on.

My question is when I can release the processor variable created above. Should I be calling autorelease. Will the control come to next line of code if I put [processor release] after this line above: [processor createRequestfromURL:url]

Note: I have a similar question before but this one has more specifics so adding it as a separate question here.


It sounds like you need the processor until the delegate call that does processData. Here's what I usually do:

  1. Declare your delegate protocol such that a reference to the object that makes the call is in the method, e.g. connectionProcessor:didProcessData:
  2. In the delegate callback, invoke release on the reference passed back in the callback.

This way the delegate decides when it's done with the object.


When to release? Release when you do not need the object anymore, otherwise you are wasting memory, its that simple.

Only use autorelease if you really need to, like in getter methods. Autorelease has some little overhead + objects you most likely won't need are kept in the memory longer. If you have a lot of autoreleased objects your iphone app might be shut down if the system memory is full. On the mac you shouldn't care too much about autorelease I guess, but its still better to only use autorelease if you really need to.

Also when you are using autorelease you gotta make sure you aren't going to use the object after he current autorelease pool is popped => EXC_BAD_ACCES crash


I haven't been working with objective-c for that long so take this with a huge pile of salt, but my guess is autorelease. Which is released when the autoreleasepool is destroyed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜