从内部块返回方法对象 [英] Returning method object from inside block
问题描述
我想知道如何正确执行以下操作:我有一个返回 NSData
对象的方法。它从 UIDocument
获取 NSData
对象。 NSData
对象可能会变大,所以我想确保它在响应开始之前已完全加载。因此,我想从块本身返回方法的值。所以类似这样:
I am wondering how to do the following correctly: I have a method that is to return an NSData
object. It gets the NSData
object from a UIDocument
. The NSData
object can get large, so I want to make sure it is fully loaded before the response starts. I would therefore like to return the value of the method from within the block itself. So something like this:
- (NSData*)getMyData {
MyUIDocument *doc = [[MyUIDocument alloc] initWithFileURL:fileURL];
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
return doc.myResponseData; // this is to be the return for the method not the block
}
}];
}
这会导致错误,因为返回
显然是指块
的返回
。
This causes an error because the return
apparently refers to the block
's return
.
如何在不必使线程阻塞等待/循环的情况下完成此操作?
How can I accomplish this without having to make a thread blocking wait/while loop?
谢谢。
推荐答案
你做不到。接受这样一个事实,即您尝试执行的操作是异步操作,并在 getMyData
方法中添加完成块参数,该方法在调用内部完成处理程序时调用。 (并从方法签名中删除 return
):
You can't. Embrace the fact that what you're trying to do is asynchronous and add a completion block parameter to your getMyData
method which is called when the inner completion handler is called. (And remove the return
from the method signature):
- (void)getMyDataWithCompletion:(void(^)(NSData *data))completion {
MyUIDocument *doc = [[MyUIDocument alloc] initWithFileURL:fileURL];
[doc openWithCompletionHandler:^(BOOL success) {
completion((success ? doc.myResponseData : nil));
}];
}
swift中存在同样的问题,你可以添加一个类似的完成块: / p>
The same problem exists in swift and you can add a similar completion block:
func getMyData(completion: ((data: NSData?) -> Void) {
data = ...
completion(data)
}
这篇关于从内部块返回方法对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!