返回数组时不兼容的块指针类型?

时间:2014-11-30 14:40:35

标签: ios objective-c parse-platform objective-c-blocks

我有一个parse.com的食物对象数据库,我正在尝试返回一个包含所有食物的数组。

- (NSArray*) allFoods {

    NSMutableArray *foodArr = [NSMutableArray array];
    PFQuery * foodQuery = [PFQuery queryWithClassName:@"Food"];
    foodQuery.limit = 5000;
    [foodQuery findObjectsInBackgroundWithBlock:^(NSArray * foods, NSError * error) {
            for (PFObject *foodRaw in foods) {
                MenuItem *food = [[MenuItem alloc] initWithName:[foodRaw valueForKey:@"name"]  andURL:nil];
                [foodArr addObject:food];
            }

        return foodArr;

    }];
}

但是,块期望void,并且我无法在不导致错误的情况下包含return语句。

Incompatible block pointer types sending 'NSMutableArray *(^)(NSArray *__strong, NSError *__strong)' to parameter of type 'PFArrayResultBlock' (aka 'void (^)(NSArray *__strong, NSError *__strong)')

1 个答案:

答案 0 :(得分:2)

你应该使用类似的东西:

typedef void (^ArrayResponseBlock)(NSArray *array);

- (void) allFoodsAsyncWithCompletion:(ArrayResponseBlock)completionBlock {

    NSMutableArray *foodArr = [NSMutableArray array];
    PFQuery * foodQuery = [PFQuery queryWithClassName:@"Food"];
    foodQuery.limit = 5000;
    [foodQuery findObjectsInBackgroundWithBlock:^(NSArray * foods, NSError * error) {
        for (PFObject *foodRaw in foods) {
            MenuItem *food = [[MenuItem alloc] initWithName:[foodRaw valueForKey:@"name"]  andURL:nil];
            [foodArr addObject:food];
        }

        completionBlock(foodArr);        
    }];
}