【问题标题】:Returning a value from a block in class method从类方法中的块返回值
【发布时间】:2015-02-12 20:26:06
【问题描述】:

我想在我的一个帮助器类中创建一个简单的方法,该方法返回一个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;

}

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

【问题讨论】:

  • 你需要重新思考你的逻辑。您不能从这样的异步方法返回值 - return 语句将在后台任务调用其块之前执行(但这不是错误的来源)。
  • 该错误是因为您需要使用__block 修饰符声明numberOfPhotos。但是“rdelmar”是正确的,即使错误被修复,代码也不会像写的那样工作。
  • @rdelmar 你认为在我的 VC 文件中创建一个方法并从那里调用它会更聪明吗?
  • 你在哪里调用它没有错;在辅助类中做这件事很好,但你需要正确地做。您要么需要从 findObjectsInBackgroundWithBlock 的完成块中调用委托方法,要么让 photoCount 方法有自己的完成块,这将在 if(objects) 子句中执行。
  • 顺便说一句 - 你为什么使用 NSString 来保存计数值?使用NSInteger

标签: ios objective-c


【解决方案1】:

你正在调用异步方法,所以你不能立即返回值,而是你想采用异步完成块模式:

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

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多