dealloc对象为什么我不能dispatch_release?

时间:2015-04-06 07:19:21

标签: ios grand-central-dispatch release

使用gcd,做一些异步作业。 当dealloc确实打电话时,在这一行" dispatch_sync(_queue,^ {})",它在线程中消失了生命。

这里是代码示例(使用ARC)。

ThingWithAQueue:

- (void)dealloc
{
    NSLog(@"Dealloc in Thing");
    dispatch_sync(_queue, ^{});//check the queue is safe
    dispatch_release(_queue);
    _queue = nil;
    NSLog(@"Dealloc in Thing, done");
}

- (void)will{
    NSLog(@"will test gcd ");
}

- (void)did{
    NSLog(@"did test gcd ");
}

- (void)addSomeWork1:(void(^)(void))work
{

    if (!_queue)
        _queue = dispatch_queue_create("com.johsrl.ThingQueue", NULL);


    dispatch_async(_queue, ^{
        [self will];
        work();
        //Since I refer to self here, dealloc will not be run until after all blocks complete
        [self did];
        NSLog(@"Work is done: %@",self);
    });

}

的ViewController:

- (IBAction)test1:(id)sender {

    ThingWithAQueue *thing = [[ThingWithAQueue alloc] init];

    [thing addSomeWork1:^{sleep(1);}];
    [thing addSomeWork1:^{sleep(1);}];
    [thing addSomeWork1:^{sleep(1);}];
    [thing addSomeWork1:^{sleep(1);}];
    [thing addSomeWork1:^{sleep(1);}];

    NSLog(@"The view controller is done with test 1.");

}

日志:

2015-04-06 14:47:17.200 GCD[18524:3570041] The view controller is done with test 1.
2015-04-06 14:47:17.200 GCD[18524:3570124] do will test gcd 
2015-04-06 14:47:18.206 GCD[18524:3570124] do did test gcd 
2015-04-06 14:47:18.206 GCD[18524:3570124] Work is done: <ThingWithAQueue: 0x7b246660>
2015-04-06 14:47:18.207 GCD[18524:3570124] do will test gcd 
2015-04-06 14:47:19.208 GCD[18524:3570124] do did test gcd 
2015-04-06 14:47:19.209 GCD[18524:3570124] Work is done: <ThingWithAQueue: 0x7b246660>
2015-04-06 14:47:19.209 GCD[18524:3570124] do will test gcd 
2015-04-06 14:47:20.209 GCD[18524:3570124] do did test gcd 
2015-04-06 14:47:20.210 GCD[18524:3570124] Work is done: <ThingWithAQueue: 0x7b246660>
2015-04-06 14:47:20.210 GCD[18524:3570124] do will test gcd 
2015-04-06 14:47:21.212 GCD[18524:3570124] do did test gcd 
2015-04-06 14:47:21.212 GCD[18524:3570124] Work is done: <ThingWithAQueue: 0x7b246660>
2015-04-06 14:47:21.212 GCD[18524:3570124] do will test gcd 
2015-04-06 14:47:22.216 GCD[18524:3570124] do did test gcd 
2015-04-06 14:47:22.216 GCD[18524:3570124] Work is done: <ThingWithAQueue: 0x7b246660>
2015-04-06 14:47:22.216 GCD[18524:3570124] Dealloc in Thing

当我点击&#34;暂停程序执行&#34; Xcode上的按钮。 节目:

enter image description here

如果我删除该行&#34; dispatch_sync(_queue,^ {}); &#34;

删除GCD阻止中的自我方法( [self did]; &amp; [self did]; ),

代码没问题。

在此线程队列中的 dispatch_sync(_queue,^ {}); 中发生了什么。

&#34; dispatch_sync(_queue,^ {});&#34;是检查队列是线程的正确方法吗?

0 个答案:

没有答案