从类方法中的块返回值

时间:2014-12-14 17:56:17

标签: ios objective-c

我想在我的一个helper类中创建一个返回NSString的简单方法,但是我无法找到返回值的正确方法。我在if语句中得到了这个错误。

  

变量不可分配(缺少__block类型说明符)

+ (NSString *) photoCount {

    NSString *numberOfPhoto = [[NSString alloc] init];

    PFQuery *photoQuery = [PFQuery queryWithClassName:@"PhotoContent"];
    [photoQuery whereKey:@"usr" equalTo:[PFUser currentUser]];
    [photoQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        if (objects) {

            numberOfPhoto = [NSString stringWithFormat:@"%d", [objects count]];

        }
    }];

    return numberOfPhoto;

}

我错了什么?我试图直接从块中返回字符串,但它没有帮助。

1 个答案:

答案 0 :(得分:2)

您正在调用异步方法,因此您无法立即返回该值,而是希望采用异步完成块模式:

+ (void) photoCountWithCompletionHandler:(void (^)(NSInteger count, NSError *error))completionHandler {
    NSParameterAssert(completionHandler);

    PFQuery *photoQuery = [PFQuery queryWithClassName:@"PhotoContent"];
    [photoQuery whereKey:@"usr" equalTo:[PFUser currentUser]];
    [photoQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects) {
            completionHandler([objects count], nil);
        } else {
            completionHandler(-1, error);
        }
    }];
}

然后当你打电话时,它会是这样的:

[MyClass photoCountWithCompletionHandler:^(NSInteger count, NSError *error) {
    if (error) {
        // handle the error here
        NSLog(@"photoCountWithCompletionHandler error: %@", error);
        self.textLabel.text = @"?";
    } else {
        // use `count` here
        self.textLabel.text = [NSString stringWithFormat:@"%ld", (long) count];
    }
}];

// do not use `count` here, as the above block is called later, asynchronously
相关问题