Joseph Joseph - 6 months ago 14
iOS Question

Returning method object from inside block

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?

Thanks.

Answer

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));
    }];
}

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

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