IOS 创建并发线程的实例详解

2020-01-21 00:12:00王冬梅

        每一个线程都需要创建一个 autorelease pool,当做是该线程第一个被创建的对象。如果不这样做,如果不这样做,当线程退出的时候,你分配在线程中的对象会发生内存泄露。为了更好的理解,我们来看看下面的代码: 


- (void) autoreleaseThread:(id)paramSender{  
NSBundle *mainBundle = [NSBundle mainBundle];  
NSString *filePath = [mainBundle pathForResource:@"AnImage"  
ofType:@"png"];  
UIImage *image = [UIImage imageWithContentsOfFile:filePath];  
/* Do something with the image */  
NSLog(@"Image = %@", image);  
}  
- (void)viewDidLoad {  
[super viewDidLoad];  
[NSThread detachNewThreadSelector:@selector(autoreleaseThread:)  
toTarget:self  
withObject:self];  
}  
如果你运行这段代码,,你就会在控制台窗口看到这样的输出信息:
*** __NSAutoreleaseNoPool(): Object 0x5b2c990 of 
class NSCFString autoreleased with no pool in place - just leaking 
*** __NSAutoreleaseNoPool(): Object 0x5b2ca30 of 
class NSPathStore2 autoreleased with no pool in place - just leaking 
*** __NSAutoreleaseNoPool(): Object 0x5b205c0 of 
class NSPathStore2 autoreleased with no pool in place - just leaking 
*** __NSAutoreleaseNoPool(): Object 0x5b2d650 of 
class UIImage autoreleased with no pool in place - just leaking

      上面的信息显示了我们创建的 autorelease 的 UIImage 实例产生了一个内存泄露,另外,FilePath 和其他的对象也产生了泄露。这是因为在我们的线程中,没有在开始的时候创建和初始化一个autorelease pool。下面是正确的代码,你可以测试一下,确保它没有内存泄露:


- (void) autoreleaseThread:(id)paramSender{  
@autoreleasepool {  
NSBundle *mainBundle = [NSBundle mainBundle];  
NSString *filePath = [mainBundle pathForResource:@"AnImage"  
ofType:@"png"];  
UIImage *image = [UIImage imageWithContentsOfFile:filePath];  
/* Do something with the image */  
NSLog(@"Image = %@", image);  
}  
}  

以上使用关于IOS 并发线程的实例,如有疑问大家可以留言讨论,共同进步,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到IOS开发频道。