用于JSON解析的NSDictionary或自定义NSObject

时间:2012-09-05 20:54:56

标签: objective-c ios json nsdictionary nsobject

我见过很多人使用NSDictionary进行JSON解析:

//ViewController.m
NSString* forename = [jsonDict valueForKey:@"forename"];
NSString* surname = [jsonDict valueForKey:@"surname"];

但我也有人从NSObject创建自定义NSDictionary

//JSONObject.h
@interface JSONObject : NSObject

@property (nonatomic) NSString* forename;
@property (nonatomic) NSString* surname;
@end

//JSONObject.m
@implementation JSONObect

@synthesize forename = _forename;
@synthesize surname = _surname;

@end

//ViewController.m
JSONObject* jsonObject = [[JSONObject alloc] init];
[jsonObject setForename:[jsonDict valueForKey:@"forename"]];
[jsonObject setSurname:[jsonDict valueForKey:@"surname"]];

然后将它们存储在NSMutableArray

NSMutableArray* jsonObjectsArray = [NSMutableArray arrayWithCapacity:20];
[jsonObjectsArray addObject:jsonObject];

如果需要,可以在以后访问。

就我而言,我有一个UITableView从JSON获取数据。数据至少使用一次,但最有可能使用更多(例如,在设备旋转时)。 JSON数据不应永久存储到文件中,因为它会定期更新,并在每次应用程序启动时下载。

我应该在我的方案中使用自定义NSObject还是NSDictionary

2 个答案:

答案 0 :(得分:0)

使用自定义Object的一个参数是,它距离使用NSManagedObject只有几步之遥,这可以让您利用Core Data来管理对象图。

答案 1 :(得分:0)

使用NSDictionary的理由是它更简单,更容易理解,并且您定义的“次要”类(以及相关的h / m文件)更少,因此在项目中管理的更少。在“不断变化”的项目中编辑/扩展也更容易。