如何从后台线程返回数据? [英] How to return data from background thread ?
问题描述
我有一个方法,应该返回一个在后台线程中填充的数组.我想等return语句,直到数组完全填充为止.我该怎么做?我知道如何处理没有返回类型的数据,但是我想调用此函数并获取填充的数组.
I have a method that should return an array which is populated in a background thread. I would like to wait with the return statement until the array is completely populated. How would I do that ? I know how to process data with no return type, but I would like to call this function and get the populated array.
示例(这里的数组最终为空,因为它在填充数组之前就返回了-我想做一些事情来返回填充的数组):
Example (Here the array ends up empty because it returns before array is populated - I would like to do something to return the populated array) :
-(NSArray*)fetchSomeArray{
__block NSArray *arrayToReturn;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,(unsigned long)NULL), ^(void) {
NSArray *someArray = ...; // getting some array from database
arrayToReturn = [NSMutableArray new];
for(int i=0;i<someArray.count;i++){
[arrayToReturn addObject:...];
}
});
return arrayToReturn;
}
推荐答案
使用委托,或阻止并取出return arrayToReturn;
.在"for"之后并在"dispatch_async"内部:
Use delegation, or blocks and take out the return arrayToReturn;
. After your "for" and inside the "dispatch_async":
dispatch_async(dispatch_get_main_queue(),^{
[myDelegate passComputedArray:arrayToReturn];
});
这篇关于如何从后台线程返回数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!