gpt4 book ai didi

ios - 在 NSOperationQueue 和 mainQueue 之间传递数据

转载 作者:行者123 更新时间:2023-11-29 10:59:18 26 4
gpt4 key购买 nike

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

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

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

问题是,考虑到内存管理,我不确定传递此数据的最佳方式是什么。 (该项目不使用 ARC)。像这样在 operationQueueArray 上使用 autorelease 是否安全:

[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];
}];
}];

用这段代码保证operationQueueArraymainQueue中不被释放吗?

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

最佳答案

  [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];
});
}];

关于ios - 在 NSOperationQueue 和 mainQueue 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707871/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com