来自块的函数返回值 [英] function return value from block
问题描述
如果我有一个返回int的函数并且int的返回值是从块中获取的,怎么办?
What if I have a function that returns an int and the return value of the int is taken from the block?
例如:
- (int) queryForKey:(NSString *)aKey view:(UIButton *)aView countView:(UIView *)aCountView counter:(int) count {
//some initialization
[query countObjectsInBackgroundWithBlock:^(int number, NSError * error) {
[aCountView addSubview:self.generateCountLabel];
if (number > 0){
[aView setUserInteractionEnabled:YES];
[aView setEnabled:YES];
}
//return number; //doing this will generate an error
}];
}
另一个问题是,如果我有一个int作为上面函数的参数传入,我想给它赋一个值怎么办?这样的事情甚至有可能吗?
also another question is, what if I have an int passed in as an argument of the function above and I would like to assign a value to it. Is some thing like that even possible?
推荐答案
问题是您有一个同步方法(一个要立即返回值的方法),该方法需要返回派生自异步方法(一个用另一种方式处理业务.
The problem is that you have a synchronous method (one that wants to return the value immediately) that needs to return a value derived from an asynchronous method (one that goes about it's business in a different thread).
有几种解决方法:
-
等待countObjectsInBackgroundWithBlock:方法完成,请按照@simonpie所述使用
__block
模式.
将return number;
替换为对生成的数字感兴趣的某个地方的调用.这也意味着queryForKey:view:countView:
可能会返回void
.
replace the return number;
with a call to something somewhere interested in the resulting number. This also means that queryForKey:view:countView:
will likely return void
.
后者是首选解决方案,因为它不会阻塞调用queryForKey:...
方法的线程.
The latter is the preferred solution as it will not block the thread calling the queryForKey:...
method.
请注意,除了主线程之外,您不能在任何其他对象上添加UIKit类.如果该块是在后台线程上执行的,则在该块中执行的操作是无效的.
Note that you can't diddle UIKit classes on anything but the main thread. If that block is executed on a background thread, then doing what you are doing in the block is invalid.
这篇关于来自块的函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!