gpt4 book ai didi

ios - 从类方法中的 block 返回值

转载 作者:行者123 更新时间:2023-11-28 21:53:16 25 4
gpt4 key购买 nike

我想在我的辅助类之一中创建一个返回 NSString 的简单方法,但我想不出返回值的正确方法。我在 if 语句中收到此错误。

Variable is not assignable (missing __block type specifier)

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

}

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

最佳答案

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

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

关于ios - 从类方法中的 block 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27472227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com