首页 > 解决方案 > 目标 c:无法将值从 Firebase 数据库存储到 NSdictionary

问题描述

这个问题类似于尝试将值从 Firebase 存储到 NSDictionary,但是在提到的链接中,我不太明白如何修复错误。我已经查看了链接的 Firebase 文档,但仍然无法弄清楚如何将从 firebase 获得的字典保存到我自己的字典中。我无法对帖子发表评论,因为我没有足够的声誉。有人可以告诉我如何解决将值从 Firebase 存储到 NSDictionary的问题吗?谢谢你

编辑:包括下面的代码片段:

#import "AllUsersProfile.h"
@import Firebase;
@import FirebaseDatabase;

@interface AllUsersProfile () <UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) UITableView * tableView;
@end


@implementation AllUsersProfile

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                                  style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate  = self;
    [self.view addSubview:self.tableView];
    
    self.ref = [[FIRDatabase database] reference];
    //to get the database and save
    [self.ref observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
        self.userData = snapshot.value;
        self.datasourceArray = [NSMutableArray array];
        NSArray *keys = [[self.userData allKeys] sortedArrayUsingSelector:@selector(compare:)];
        for (NSString *key in keys) {
            [self.datasourceArray addObject:self.userData[key]];
        }
   
        NSLog(@"%@",self.datasourceArray); //able to print here
        NSLog(@"%@",self.userData); //able to print here
    }];

    NSLog(@"%@",self.datasourceArray); //unable to print, gives null
    NSLog(@"%@",self.userData); //unable to print here as well, gives null
}

所以我在 .h 文件中将 userData 定义为属性(NSMutableDictionary),并将 datasourceArray 定义为 NSMutableArray 作为属性。

    @property (strong, nonatomic) NSMutableArray *datasourceArray;
    @property (strong, nonatomic) NSMutableDictionary * userData

在循环中,我可以打印 Firebase 的内容。但是,如果我尝试在从 Firebase 获取数据的循环之外访问它们,它们将返回 null,我不知道为什么。

标签: objective-cfirebase

解决方案


推荐阅读