ios - 返回 NSString 时如何解决不兼容的 block 指针类型编译器错误?

标签 ios objective-c firebase-realtime-database nsstring

我试图用这个方法返回一个变量 fifeScore,但我一直收到错误:

Incompatible block pointer types sending 'NSString *(^)(FIRDataSnapshot *__strong)' to parameter of type 'void (^ _Nonnull)(FIRDataSnapshot * _Nonnull __strong)'

+(NSString *)getFifeScoreForUserWithUID:(NSString *)uid {

    FIRDatabaseReference *scoreRef = [[[[FIRDatabase database] reference] child:@"Scores"] child:uid];
    [scoreRef observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {

        NSString * fifeScore;

        if(snapshot.exists){
            NSString * tempScore = [snapshot.value objectForKey:@"fifeScore"];
            fifeScore = [NSString stringWithFormat:@"%@",tempScore];
        } else {
            fifeScore = @"0";
        }
        return fifeScore;
    }];

}

当我注释掉 return 语句时,错误消失了。这是我第一次尝试编写返回字符串的方法。这里有什么问题,我该如何解决错误?

最佳答案

在这种情况下你应该使用 block 。

+(void)getFifeScoreForUserWithUID:(NSString *)uid completionBlock:(void(^)(NSString *score))completion {

  FIRDatabaseReference *scoreRef = [[[[FIRDatabase database] reference] child:@"Scores"] child:uid];
  [scoreRef observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {

    NSString * fifeScore;

    if(snapshot.exists){
      NSString * tempScore = [snapshot.value objectForKey:@"fifeScore"];
      fifeScore = [NSString stringWithFormat:@"%@",tempScore];
    } else {
      fifeScore = @"0";
    }

    if (completion) {
      completion(fifeScore)
    }
  }];
}

用法:

[YOUR_CLASS getFifeScoreForUserWithUID:YOUR_UID completionBlock:^(NSString *score) {
  NSLog(@"%@", score);
}];

关于ios - 返回 NSString 时如何解决不兼容的 block 指针类型编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125517/

相关文章:

ios - UIMenuController,它的目标在哪里?使困惑

ios - 不能在 swift 中划分两个 NSNumbers?

iOS:Instruments 显示 imageio_png_data 的大小比其实际图像大小大 300 倍

ios - 将整个 Xcode 工程做成一个库供外部集成

iphone - 需要 iPhone 屏幕录制

ios - 追加数组 NSDictionary 时出错

objective-c - NSTimer + 模态问题

javascript - 错误 : Paths must be non-empty strings and can't contain ".", "#"、 "$"、 "["或 "]"(ionic 2 和 firebase)

android - 从 firebase 数据库填充 textView

ios - Firebase 未按正确顺序下载 gif - iOS