1

我想返回一个数组,其内容是在 dispatch_sync 块期间设置的。

我通常看到的代码是这样的:

-(NSArray *)getSomeLockedList {

    __block NSArray *resultList;

    dispatch_sync(myQueue, ^{   
       // copy contents of my ivar NSMutableArray into return variable  
       resultList = [ivarContentList copy]; 
    });

    // add auto-release since a 'copy' was done within block
    return [resultList autorelease]; 
}

如果我不是在复制一个完整的数组,而是想一个一个地添加,我可以跳过返回值上的“自动释放”吗?

-(NSArray *)getSomeLockedList {

    __block NSArray *someResultKeys; // is it ever safe to do the alloc here?

    dispatch_sync(myQueue, ^{       
       someResultKeys = [NSMutableArray array];

    for (id entry in ivarContentList) {

          // do some work on entry instance
          [someResultKeys addObject:entry];     
       }        
    });

    return someResultKeys; // autorelease not necessary?
}

dispatch_sync 块中的 [NSMutableArray 数组] 分配是否安全,以便在此方法完成堆栈后继续使用结果?

4

2 回答 2

3

不,这不安全。问题是,当您分派到队列上时,该队列上自动释放的任何对象都将在该队列的 NSAutoreleasePool 耗尽时被收集。你无法控制这将是什么时候。考虑这一点的适当方法是始终假设自动释放池将在您的块在队列上完成执行时耗尽。

在您的情况下处理此问题的正确方法是使用

someResultKeys = [[NSMutableArray alloc] init];

在队列中,然后[someResultKeys autorelease]在 dispatch_sync 之后调用。

于 2011-01-10T21:27:11.283 回答
0

这更容易通过编写来避免 __block 变量

NSMutableArray* someResultKeys = [NSMutableArray array];

outside the block. However, I wonder about the dispatch_sync. You know that dispatch_sync will wait until the block finishes executing? (And in case of a serial queue, that means all blocks before it have finished executing as well). Is there a good reason why you don't call the code directly?

于 2014-03-20T18:03:37.423 回答