Obj-C类方法来自块 [英] Obj-C class method results from block

查看:77
本文介绍了Obj-C类方法来自块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道此函数首先返回图像",然后"findObjectsInBackgroundWithBlock"检索数据,这就是结果为零的原因.

I understand that this function first return "images" then "findObjectsInBackgroundWithBlock" retrieve data that's why results is nil.

1-如何从块返回数组?
2-如何将该块放在主线程之外?

1 - how to return array from block?
2 - how to put this block not in main thread?

+(NSMutableArray *)fetchAllImages{
        __block NSMutableArray *images = [NSMutableArray array];
        PFQuery *query = [PFQuery queryWithClassName:@"Photo"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                for (PFObject *object in objects) {
                    PFFile *applicantResume = object[@"imageFile"];
                    NSData *imageData = [applicantResume getData];
                    NSString *imageName = [ImageFetcher saveImageLocalyWithData:imageData FileName:object.objectId AndExtention:@"png"];
                    [images addObject:imageName];
                    // here images is not empty
                }
            } else {
                NSLog(@"Error: %@ %@", error, [error userInfo]);
            }
        }];
        // here images is empty
        return images;
    }

推荐答案

该方法异步执行其工作,并且调用方需要知道这一点.所以,

The method performs its work asynchronously, and the caller needs to know that. So,

不要:

+(NSMutableArray *)fetchAllImages{

返回数组,因为返回时数组尚未准备就绪.

return an array, because the array is not ready at the time of return.

做:

+ (void)fetchAllImages {

不返回任何内容,因为这是方法完成执行后所拥有的.

return nothing, because that's what you have when the method finishes execution.

但是如何将图像提供给呼叫者? findObjectsInBackgroundWithBlock的相同方法,以及稍后运行的代码块....

But how to give the images to the caller? The same way that findObjectsInBackgroundWithBlock does, with a block of code that runs later....

做:

+ (void)fetchAllImagesWithBlock:(void (^)(NSArray *, NSError *)block {

然后,在findBlock中使用您的代码:

Then, using your code from within the findBlock:

[images addObject:imageName];
// here images is not empty
// good, so give the images to our caller
block(images, nil);  

// and from your code, if there's an error, let the caller know that too
NSLog(@"Error: %@ %@", error, [error userInfo]);
block(nil, error);

现在您的内部调用者调用此方法,就像您的提取代码调用解析一样:

Now your internal caller calls this method just like your fetch code calls parse:

[MyClassThatFetches fetchAllImagesWithBlock:^(NSArray *images, NSError *error) {
    // you can update your UI here
}];

关于主线程的问题:您希望网络请求从主线程运行,并且确实如此.您希望在完成后运行的代码可以在主体上运行,以便可以安全地更新UI.

Regarding your question about the main thread: you want the network request to run off the main, and it does. You want the code that runs after it finishes to run ON the main, so you can safely update the UI.

这篇关于Obj-C类方法来自块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆