Search code examples
iosfirebase-realtime-databasensdictionarynsobject

Use NSDictionary values between two class


I'm trying to get the values ​​within an NSDictionary between two classes ..

I use this method in the Database.m (NSObject class)

+(void)fetchAllUserWithReference:(NSDictionary *)dictionary {

    FIRDatabaseReference *userReference = [[[FIRDatabase database] reference] child:RTDUSER];
    [userReference observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
        __block NSDictionary *dict = dictionary;
        dict = snapshot.value;

    } withCancelBlock:nil];
}

and I want to get the NSDictionary data in the Dashboard.m (UIView Controller) class like this ..

-(void)retrieveUsers {
    NSDictionary *dict = [[NSDictionary alloc] init];
    [Database fetchAllUserWithReference:dict];    
    NSLog(@"DICT %@",dict);
}

Why is my NSDictionary of class Dashboard.m always NULL ?? Where am I wrong?


Solution

  • You can use completion handler to get values back after executing block.

    -(void)fetchAllUserWithReference:(NSDictionary *)param
           withCompletionHandler:(void (^)(NSDictionary *response))block{
    
           FIRDatabaseReference *userReference = [[[FIRDatabase database] reference] child:RTDUSER];
          [userReference observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
           NSDictionary *dict = snapshot.value;
           block(dict);
        } withCancelBlock:
       block(nil);];
    }
    
    -(void)retrieveUsers {
        NSDictionary *dict = [NSDictionary init];
        [self fetchAllUserWithReference:dict withCompletionHandler:^(NSDictionary *response) {
            NSLog(@"%@",response);
        }];
    }