如何在GCD块中指定返回类型?在这里,我想将结果作为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; }
块的格式(参数/返回类型)在函数的签名中指定.在这种情况下,dispatch_sync使用没有返回类型且没有参数的块.如果您想要使用更多变量,则需要在块外部声明它们,如上面的代码所示.@H_404_11@