【问题标题】:Use Variable outside Firebase Block在 Firebase 块外使用变量
【发布时间】:2018-04-18 16:05:59
【问题描述】:

大家好,我正在为我的 ios 项目使用 Firebase ... 当我查询数据库时,我在使用 Firebase 块之外的变量值时遇到了很多麻烦。

例如,在这种情况下,我试图从这个查询中获取一个数字值...

 FIRDatabaseReference *userDbRef = FIRDatabase.database.reference;
 [[[userDbRef child:RTDUSER] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

     NSUInteger totalCFU = [snapshot.value[RTDUSER_TOTALCFU] unsignedIntegerValue];

} withCancelBlock:nil];

我需要这个数值也在块外获得(在这个类的其他函数中)...

如何在 firebase 块之外使用 TotalCFU 变量?

【问题讨论】:

    标签: ios firebase block nsuinteger


    【解决方案1】:

    您可以从块内部调用方法来处理值。

    FIRDatabaseReference *userDbRef = FIRDatabase.database.reference;
     [[[userDbRef child:RTDUSER] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    
        NSUInteger totalCFU = [snapshot.value[RTDUSER_TOTALCFU] unsignedIntegerValue];
    
        // Call a function to handle value
        [self doSomethingWithCFU: totalCFU];
    
    } withCancelBlock:nil];
    

    你班上的其他地方:

    (void)doSomethingWithCFU:(NSUInteger)totalCFU {
        // Do something with the value
    }
    

    【讨论】:

    • 您好,我尝试了您的建议,但如果我在块(外部)之后立即插入 nslog,totalCFU 将返回零值
    • 正确,该值在块执行时设置。听起来您可能更喜欢我提到的替代方法。创建一个处理新值的方法。
    • 好的,所以我不能通过保持相同的方法管理块外的变量?
    • 没有。调用异步发生。到它完成时,您将退出该方法。
    • 好的,那么当你写这篇文章时,你是什么意思“在街区之外”? // 设置值,使其可以在块外访问
    【解决方案2】:

    使用__block 在外部使用您的变量。

    FIRDatabaseReference *userDbRef = FIRDatabase.database.reference;
    __block NSUInteger totalCF;
    [[[userDbRef child:RTDUSER] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    
         totalCFU = [snapshot.value[RTDUSER_TOTALCFU] unsignedIntegerValue];
    
    } withCancelBlock:nil];
    

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多