创建并发线程
看个例子
- (void) autoreleaseThread:(id)paramSender{
@autoreleasepool {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"img1"
ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
/* Do something with the image */
NSLog(@"Image = %@", image);
}
}
-(void)test6_16
{
[NSThread detachNewThreadSelector:@selector(autoreleaseThread:)
toTarget:self
withObject:self];
}
输出:
2014-03-13 14:46:51.536 cookbook[579:360b] Image = <UIImage: 0x8c4a870>
当然了,mainbundle里面要有那个文件才行,不然会Image = NULL的。
这里要注意的是,因为是在子线程中运行,必须要自己创建自动释放池。否则线程执行完后,线程内创建的对象将造成内存泄露。
比如把autoreleasepool去掉,按下面这样写:
- (void) autoreleaseThread:(id)paramSender{
// @autoreleasepool {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"img1"
ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
/* Do something with the image */
NSLog(@"Image = %@", image);
// }
}
-(void)test6_16
{
[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
不过很悲剧,在我的电脑上没有试出来,还是很完美的打印了
2014-03-13 14:53:32.577 cookbook[616:360b] Image = <UIImage: 0x8c746a0>
不知道是不是高版本的编译器在detachNewThread时自动把autoreleasepool给加上去了。
不过为了保险起见,我们还是自己加上去吧,毕竟没啥坏处。