gpt4 book ai didi

objective-c - 如何在 GCD block 中指定返回类型

转载 作者:可可西里 更新时间:2023-11-01 03:38:53 25 4
gpt4 key购买 nike

如何在 GCD block 中指定返回类型?在这里,我想将结果返回为 NSData ...

- (NSData *)returnData:(NSString *)urlString{
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_sync(concurrentQueue, ^{ // here return type showing error

NSString *strUrl = urlString;
if([strUrl length] == 0)
return nil; // from this point i want to stop the execution of the block and return nil .

// otherwise only continue the left operations



});
}

最佳答案

- (NSData *)returnData:(NSString *)urlString {
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// Declare your local data outside the block.
// `__block` specifies that the variable can be modified from within the block.
__block NSData *localData = nil;

dispatch_sync(concurrentQueue, ^{
// Do something with `localData`...
localData = somethingWonderful;
});

// `localData` now contains your wonderful data.
return localData;
}

block 的格式(参数/返回类型)在函数的签名中指定。在这种情况下,dispatch_sync 使用了一个没有返回类型和参数的 block 。如果您希望使用更多变量,您需要在 block 外声明它们,如上面的代码所示。

关于objective-c - 如何在 GCD block 中指定返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8347904/

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