开发者

How to handle leaks when using a multiple threads in iphone?

开发者 https://www.devze.com 2023-01-29 06:33 出处:网络
I have called a method in separate thread in viewdidload method [NSThread detachNewThreadSelector:@selector(callWebService) toTarget:self withObject:nil];

I have called a method in separate thread in viewdidload method

[NSThread detachNewThreadSelector:@selector(callWebService) toTarget:self withObject:nil]; 

-(void)callWebService{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
 [NSThread detachNewThreadSelector:@selector(loadImages) toTar开发者_开发百科get:self withObject:nil]; 
 [pool release];
  }
-(void)loadImages{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    [self performSelectorOnMainThread:@selector(reloadTable) withObject:nil waitUntilDone:false];  
[pool release];
 }
 -(void)reloadTable
  {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

[myTableView reloadData];
[pool release];

}

How to handle leaks while using thread? I want to use threads.

Errors

*** __NSAutoreleaseNoPool(): Object 0x604b830 of class NSCFString autoreleased with no pool in place - just leaking

*** -[NSAutoreleasePool release]: This pool has already been drained, do not release it (double release).


The autorelease pool must be drain, not release. So I think if you change it to [pool drain] it should be working fine.


Don't know if you found your answer yet, but as I had hit something similar to your problem, I did some looking. It seems that when you drain a pool, that is (effectively) equivalent to releasing it. The documentation on the class says:

Since you cannot retain an autorelease pool (or autorelease it—see retain and autorelease), draining a pool ultimately has the effect of deallocating it.

So, you should only drain a pool once. If you need another context after that point, you should generate a new pool in the same way you generated one earlier in your code.

If there is no pool available, then you can end up leaking (as you mentioned). However, autorelease calls should log a warning message in that instance. Regarding threads, the documentation has this to say

The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

Hope this helps.

0

精彩评论

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