6.16 Creating Concurrency with Threads


创建并发线程

看个例子

- (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给加上去了。

不过为了保险起见,我们还是自己加上去吧,毕竟没啥坏处。












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值