1

我环顾四周想得到一个确切的答案,但找不到。

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

我有一个繁重的计算任务,它在操作队列中运行以计算数组。我想将结果传递回主队列并将它们用作 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此代码中发布?

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

4

2 回答 2

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];
     });
  }];
于 2013-05-23T07:50:51.007 回答
1

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

于 2013-05-23T07:43:41.510 回答