本文介绍了从块内部返回方法对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何正确执行以下操作:我有一个返回 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
    }
  }];
}

这会导致错误,因为 return 显然是指 blockreturn.

This causes an error because the return apparently refers to the block's return.

如何在不必使线程阻塞等待/while 循环的情况下完成此操作?

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 中存在,你可以添加一个类似的完成块:

The same problem exists in swift and you can add a similar completion block:

func getMyData(completion: ((data: NSData?) -> Void) {
    data = ...
    completion(data)
}

这篇关于从块内部返回方法对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:57