问题:使用 Grand Central Dispatch (GCD) 将数据(除了原语)传递到后台任务的首选/最佳/接受的做法是什么?
我对目标 C 块的关注是:块访问的变量被复制到堆上的块数据结构中,以便块以后可以访问它们。复制的指针引用可能意味着多个线程正在访问同一个对象。
我对目标 C 和 iOS 还很陌生,但我不是新线程(C++、Java、C、C#)。
代码集 #1(范围的原始副本)
//Primitive int
int taskIdBlock = self->taskNumber;
//declare a block that takes in an ID and sleep time.
void (^runTask)(int taskId, int sleepTime);
//Create and assign the block
runTask = ^void(int taskId, int sleepTime)
{
NSLog(@"Running Task: %d", taskId);
// wait for x seconds before completing this method
[NSThread sleepForTimeInterval:sleepTime];
//update the main UI
//tell the main thread we are finished with this task.
dispatch_async(dispatch_get_main_queue(), ^
{
NSLog(@"Completed Task %d",taskId);
});
};
//Get the global concurrent dispatch queue and launch a few tasks
dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//TASK #1
//increment the task number and log
NSLog(@"Create Task Number %d", ++taskIdBlock);
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(taskIdBlock,5);
});
//TASK #2
//increment the task number and log
NSLog(@"Create Task Number %d", ++taskIdBlock);
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(taskIdBlock,3);
});
输出:
Create Task Number 1
Create Task Number 2
Running Task: 1
Running Task: 2
Completed Task 2
Completed Task 1
代码集 #2(范围内的对象引用副本)
//Integer Object
NSInteger *taskIdBlock = &(self->taskNumber);
//declare a block that takes in an ID and sleep time.
void (^runTask)(int taskId, int sleepTime);
//Create and assign the block
runTask = ^void(int taskId, int sleepTime)
{
NSLog(@"Running Task: %d", taskId);
// wait for x seconds before completing this method
[NSThread sleepForTimeInterval:sleepTime];
//update the main UI
//tell the main thread we are finished with this task.
dispatch_async(dispatch_get_main_queue(), ^
{
NSLog(@"Completed Task %d",taskId);
});
};
//Get the global concurrent dispatch queue and launch a few tasks
dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//TASK #1
//increment the task number and log
NSLog(@"Create Task Number %d", ++(*taskIdBlock));
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(*taskIdBlock,5);
});
//TASK #2
//increment the task number and log
NSLog(@"Create Task Number %d", ++(*taskIdBlock));
//dispatch the task to the global queue.
dispatch_async(globalConcurrentQueue, ^{
runTask(*taskIdBlock,3);
});
输出:
Create Task Number 1
Running Task: 2
Create Task Number 2
Running Task: 2
Completed Task 2
Completed Task 2
注意每段代码的第一行。对象 NSinteger 的原始 int。我希望看到这样的东西:
dispatch_async(globalConcurrentQueue,runTask(*taskIdBlock,3));
但是,这不会编译。我只能看到这在未来变得越来越困难,所以最好先找到一个可靠的例子。提前致谢。