我相信是在 2012/2013 年,Apple 报道了一段关于代码实践的精彩视频,其中强调的一个子主题是处理 JSON 对象并为它们创建数据对象的一种很好的智能方法。抱歉,我忘记了实际视频的名称,如果有人记得,请帮我编辑答案。
Apple 所涵盖的是拥有一个存储每个 json 对象的数据对象。然后,我们将创建一个数组来存储这些对象,并在填充我们的 tableView 时适当地访问所需的字段。所以在你的情况下,你会做这样的事情。
在您的项目导航器中添加一个 NSObject 类型的文件并添加以下代码:
#import <Foundation/Foundation.h>
@interface PlaceDataObject : NSObject
-(id)initWithJSONData:(NSDictionary*)data;
@property (assign) NSInteger placeId;
@property (strong) NSString *placeName;
@property (strong) NSString *placeCity;
@property (strong) NSString *placeDay;
@end
并在您的 .m 文件中添加此代码
#import "PlaceDataObject.h"
@implementation PlaceDataObject
@synthesize placeId;
@synthesize placeName;
@synthesize placeCity;
@synthesize placeDay;
-(id)initWithJSONData:(NSDictionary*)data{
self = [super init];
if(self){
//NSLog(@"initWithJSONData method called");
self.placeId = [[data objectForKey:@"id"] integerValue];
self.placeName = [data objectForKey:@"name"];
self.placeCity = [data objectForKey:@"city"];
self.placeDay = [data objectForKey:@"day"];
}
return self;
}
@end
您现在拥有的是一个数据对象类,您可以在代码中任何需要的地方使用它,并为您显示的任何表获取适当的详细信息,无论是city 字段表还是city and name 表等. 通过这样做,您还可以避免在项目中到处都有 json 解码代码。当你的“钥匙”的名字改变时会发生什么?无需通过代码来纠正所有密钥,您只需转到 PlaceDataObject 类并更改适当的 key,您的应用程序将继续工作。
Apple 很好地解释了这一点:
“模型对象代表特殊的知识和专长。它们保存应用程序的数据并定义操作该数据的逻辑。设计良好的 MVC 应用程序将其所有重要数据封装在模型对象中......它们代表与特定问题领域相关的知识和专长,它们往往是可重用的。”
为来自服务器的每个 json 条目使用自定义对象填充您的数组
现在开始填充您制作的自定义数据对象的数组。现在遵循 MVC 方法,最好将所有处理数据的方法放在不同的类中,即 Model 类。这就是 Apple 建议将这些方法放在一个单独的模型类中进行所有处理的原因。
但现在我们只是将以下代码添加到视图控制器中,仅用于演示目的。
在视图控制器的 m 文件中创建一个方法来处理您的 JSON 数组。
//make sure you have a global NSMutableArray *placesArray in your view controllers.h file.
-(void)setupPlacesFromJSONArray:(NSData*)dataFromServerArray{
NSError *error;
NSMutableArray *placesArray = [[NSMutableArray alloc] init];
NSArray *arrayFromServer = [NSJSONSerialization JSONObjectWithData:dataFromServerArray options:0 error:error];
if(error){
NSLog(@"error parsing the json data from server with error description - %@", [error localizedDescription]);
}
else {
placesArray = [[NSMutableArray alloc] init];
for(NSDictionary *eachPlace in arrayFromServer)
{
PlaceDataObject *place = [PlaceDataObject alloc] initWithJSONData:eachPlace];
[placesArray addObject:place];
}
//Now you have your placesArray filled up with all your data objects
}
}
你会这样调用上面的方法:
//This is not what your retrievedConnection method name looks like ;)
// but you call the setupPlacesFromJSONArray method inside your connection success method
-(void)connectionWasASuccess:(NSData *)data{
[self setupPlacesFromJSONArray:data];
}
使用您的自定义数据对象填充您的 tableView
至于在 TableView 中填充数据,您可以这样做:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//We check against table to make sure we are displaying the right number of cells
// for the appropriate table. This is so that things will work even if one day you
//decide that you want to have two tables instead of one.
if(tableView == myCitysTable){
return([placesArray count]);
}
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if(cell)
{
//set your configuration of your cell
}
//The beauty of this is that you have all your data in one object and grab WHATEVER you like
//This way in the future you can add another field without doing much.
if([placesArray count] == 0){
cell.textLabel.text = @"no places to show";
}
else{
PlacesDataObject *currentPlace = [placesArray objectAtIndex:indexPath.row];
cell.textLabel.text = [currentPlace placeCity];
// in the future you can grab whatever data you need like this
//[currentPlace placeName], or [currentPlace placeDay];
}
return(cell);
}
简短的免责声明:上面的代码尚未经过测试,但如果一切正常,或者我是否遗漏了任何字符,请告诉我。