在NSOperationQueue和mainQueue之间传递数据

时间:2013-05-23 07:20:19

标签: ios memory-management nsoperationqueue

我很好地环顾四周,得到了一个确切的答案,但却找不到。

简而言之:将数据从操作队列传递到主队列的最佳方法是什么?

我有一个繁重的计算任务,它在一个操作队列中运行来计算一个数组。我想将结果传递回主队列,并在那里使用它们作为UITableView的基础。

问题在于我不确定在考虑内存管理的情况下传递此数据的最佳方法是什么。 (该项目不使用ARC)。在autorelease operationQueueArray上使用[operationQueue addOperationWithBlock:^{ NSMutableArray *operationQueueArray = [[[NSMutableArray alloc] init] autorelease]; // do some heavy compute and fill the results into the operationQueueArray [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // passing the data [mainQueueArray removeAllObjects]; [mainQueueArray addObjectsFromArray:operationQueueArray]; [myTableView reloadData]; }]; }]; 是否安全?

operationQueueArray

是否可以保证使用此代码在mainQueue中未发布{{1}}?

或者我应该在某处放一些手动版本?有更好的方法甚至指导如何做到这一点?

2 个答案:

答案 0 :(得分:1)

您正在使用传递给operationQueueArray的{​​{1}}内部块,因此它将被保留(除非您使用[[NSOperationQueue mainQueue] addOperationWithBlock:]说明符,否则将保留块中引用的所有对象。因此,您不必担心__block在另一个线程(operationQueueArray使用的线程)中自动释放。

答案 1 :(得分:1)

  [operationQueue addOperationWithBlock:^{
     NSMutableArray *operationQueueArray = [[[NSMutableArray alloc] init] autorelease];
     // do some heavy compute and fill the results into the operationQueueArray
     // If you log current thread here it should be a worker thread
     // do a sync call to your main thread with the computed data. Your async thread will not release its context, data, etc untill you finsihed passsing your data,
     // in other words, untill the dispatch_sync block does not finish
     dispatch_queue_t mainQueue = dispatch_get_main_queue();
     dispatch_sync(mainQueue, ^{
        // passing the data
        // If you do a log for [NSThread currentThread] here, it should be your main thread (UI thread)
        // It's safe to pass data to your table view as log as you retain your objects in your Table view controller data source array once you pass them there
        // and release them when your controller is released
        [mainQueueArray removeAllObjects];
        [mainQueueArray addObjectsFromArray:operationQueueArray];
        // Adding your objects to your main queue array will do +1 retain count to your objects.
        // They will only get released when your array is released.
        [myTableView reloadData];
     });
  }];