【发布时间】:2014-01-22 04:28:11
【问题描述】:
我的应用程序的一部分获取JSON 数据并使用它来显示更新。最初的JSON 响应有两个部分:错误和更新部分。
以下是你在做[JSONData objectForKey:@"updates"];隔离更新部分时得到的数组
{
2 = {
message = "Best restaurant ever!";
name = " ";
profilePictureURL = "<null>";
restPictureURL = "http://i.imgur.com/QpyMRwY.jpg";
restaurant = "someplace";
timestamp = 1390194000;
};
3 = {
message = "Ehh.";
name = " ";
profilePictureURL = "<null>";
restPictureURL = "http://i.imgur.com/QpyMRwY.jpg";
restaurant = "someplace";
timestamp = 1389848400;
};
4 = {
message = "";
name = " ";
profilePictureURL = "<null>";
restPictureURL = "http://i.imgur.com/QpyMRwY.jpg";
restaurant = "McDonald's";
timestamp = 1390346335;
};
5 = {
message = "Service was slow.";
name = " ";
profilePictureURL = "<null>";
restPictureURL = "http://i.imgur.com/QpyMRwY.jpg";
restaurant = "Bad pizzaplace";
timestamp = 1389330000;
};
}
然后我将此NSArray 传递给一个函数,该函数将其格式化为我为更新而设计的类,然后将该更新附加到存储在AppDelegate 中的NSMutableArray。
@implementation Update
+(void) appendUpdates:(NSArray*)data
{
AppDelegate* appDelegate= [[UIApplication sharedApplication]delegate];
for (NSDictionary* currentUpdate in data)
{
Update* formattedUpdate = [[Update alloc]initWithDict:currentUpdate];
[appDelegate.updateList addObject:formattedUpdate];
}
}
-(id) initWithDict:(NSDictionary*)update
{
self = [super init];
self.name = [update objectForKey:@"name"];
self.restaurant = [update objectForKey:@"restaurant"];
self.message = [update objectForKey:@"message"];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:(int)[update objectForKey:@"timestamp"]];
self.timestamp = date;
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
self.dateComponents = components;
self.profilePictureURL = [update objectForKey:@"profilePictureURL"];
self.restaurantPictureURL = [update objectForKey:@"restPictureURL"];
return self;
}
@end
当我运行代码时,我在尝试使用 objectForKey: 时在初始化方法中收到错误。
有什么想法吗?提前致谢
【问题讨论】:
-
错误是什么意思?
-
-[__NSCFString allKeys]: unrecognized selector sent to instance 0x9bc5380 2014-01-21 23:55:25.938 MyApp[49350:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString allKeys]: unrecognized selector sent to instance 0x9bc5380' -
@JasonMarmon :看看 JSON 格式。在我的回答中。
-
格式化代码时遇到了什么麻烦?很简单:粘贴,选择代码,点击源代码按钮。
标签: ios objective-c json parsing