2015-02-08 78 views
0

我知道这个函数首先返回“图像”,然后“findObjectsInBackgroundWithBlock”检索数据,这就是为什么结果为零。Obj-C类的方法结果从块

1 - 如何从块返回数组?
2 - 如何把这个块不在主线程中?

+(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; 
    } 

回答

0

它不起作用。

您正在调用异步方法。你不能等待一个异步方法的结果并返回结果(当然,如果你问的是如何在stackoverflow上进行操作的话,也可以,但不行)。使用异步块,您可以触发一个操作,并且完成功能块将在需要时提供结果。

有一些示例如何在stackoverflow上做到这一点。寻找他们是你的工作。

1

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

不要:

+(NSMutableArray *)fetchAllImages{ 

返回数组,因为数组是不是准备在返回的时间。

务必:

+ (void)fetchAllImages { 

任何回报,因为这是你有什么当方法执行完毕。

但如何将图像给调用者?同样的方式,findObjectsInBackgroundWithBlock确实,与后来运行的代码块....

务必:

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

然后,用你的代码从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); 

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

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

Regar回答关于主线程的问题:你想让网络请求跑掉主线程,并且确实如此。您希望在完成后运行的代码在main上运行,以便您可以安全地更新UI。

+0

谢谢你:) – 2015-02-08 19:18:29