代码之家  ›  专栏  ›  技术社区  ›  Austin Berenyi

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

  •  1
  • Austin Berenyi  · 技术社区  · 8 年前

    我试图返回一个变量 fifeScore 使用此方法,但我不断得到错误:

    发送“NSString”的块指针类型不兼容 *(^)(FIRDataSnapshot*\uu strong)“”到类型为“void(^\u Nonnull)(FIRDataSnapshot*\u Nonnull \uu 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 语句错误消失。这是我第一次尝试编写返回字符串的方法之一。这里有什么问题,如何解决错误?

    1 回复  |  直到 8 年前
        1
  •  1
  •   trungduc 邱林和    8 年前

    在这种情况下,应该使用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);
    }];