【发布时间】:2020-07-04 01:40:38
【问题描述】:
我正在尝试从 firebase 获取一些数据库值,但是当我尝试将这些值存储在 NSArray 中时,它会写入第一个值,然后用新值覆盖它并再次复制该值,我一直在尝试至少一个半小时试图克服这个问题。任何帮助将不胜感激。谢谢!
代码:
databaseContents = [NSArray new];
FIRDatabaseReference *ref = [[FIRDatabase database] reference];
[[ref child:@"posts"] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
for (FIRDataSnapshot *children in snapshot.children) {
NSDictionary *snapshotAsDict = [children value];
NSString *postTitle = [snapshotAsDict valueForKey:@"Title"];
NSString *postBody = [snapshotAsDict valueForKey:@"Body"];
Post *post = [[Post alloc] initWithPostTitle:postTitle initWithPostBody:postBody];
// [databaseContents addObject:post];
databaseContents = [databaseContents arrayByAddingObject:post];
for (post in databaseContents) {
NSLog(@"%@", [post getPostBody]);
}
}
[[self tableView] reloadData];
}];
JSON:
{
"posts": {
"127k9": {
"Body": "This is another post",
"Title": "Test"
},
"17a32b": {
"Body": "This is a post from the database, you did it!",
"Title": "Well Done!"
}
}
}
来自 NSLog 的结果:
2020-07-04 02:35:00.970071+0100 AppName [27829:919355] This is value1
2020-07-04 02:35:00.970390+0100 AppName [27829:919355] This is value2
2020-07-04 02:35:00.970557+0100 AppName[27829:919355] This is value2
【问题讨论】:
-
嘿里斯。你能解释一下那个输出是出乎意料的吗?另请注意,我们看不到您的数据库,因此如果输出与此相关,您需要在
posts添加 JSON(作为文本,请不要截图)。您可以通过单击Firebase Database console 上溢出菜单 (⠇) 中的“导出 JSON”链接来获取此信息。 -
您好,在数据库端看起来一切都很好,只是在 iOS 端,特别是当我将它附加到列表时。我认为我对我在这个问题中尝试做的事情的描述性不够。这是 json
{ "posts" : { "127k9" : { "Body" : "This is another post", "Title" : "Test" }, "17a32b" : { "Body" : "This is a post from the database, you did it!", "Title" : "Well Done!" } } }我正在尝试使用名为 Post 的自定义对象将两个帖子的正文和标题放入 NSArray。 -
谢谢。不过,日志现在与 JSON 完全不匹配,所以很难说发生了什么,也很难说你期望它输出什么。
标签: ios objective-c firebase firebase-realtime-database