0

Hello everyone I'm using Firebase for my ios project ... I have a lot of trouble using the values of my variables outside of the Firebase blocks when I query the database.

For example in this case I'm trying to get a number value from this query ...

 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];

I need this number value also obtained outside the block (in other functions of this class) ...

How can I use the TotalCFU variable outside the firebase block?

kAiN
  • 2,559
  • 1
  • 26
  • 54

2 Answers2

1

You can call a method from inside the block to handle the value.

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];

Somewhere else in your class:

(void)doSomethingWithCFU:(NSUInteger)totalCFU {
    // Do something with the value
}
picciano
  • 22,341
  • 9
  • 69
  • 82
  • Hello I tried your suggestion but if I insert a nslog immediately after the block (outside) totalCFU returns me a value of ZERO – kAiN Apr 18 '18 at 16:29
  • Correct, the value gets set when the block executes. Sounds like you might prefer the alternative approach I mentioned. Create a method to handle the new value. – picciano Apr 18 '18 at 16:31
  • Ok so I can not manage the variable out of the block by staying in the same method? – kAiN Apr 18 '18 at 16:32
  • No. The call happens asynchronously. By the time it completes, you will be out of that method. – picciano Apr 18 '18 at 16:36
  • ok so what do you mean "outside the block" when you write this? // Set value so that it can be accessed outside of block – kAiN Apr 18 '18 at 17:42
1

Use __block to use your variable outside.

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];
badhanganesh
  • 3,427
  • 3
  • 18
  • 39