这就是我要做的:
创建一个自定义初始化NewModelClass
为了将其从这部分代码中删除。这样,如果你必须创建一个新对象NewModelClass
,您不必重写所有行。
In 新模型类.h:
-(id)initWithJSONDict:(NSDictionary *)dict;
In 新模型类.m:
-(id)initWithJSONDict:(NSDictionary *)dict
{
self = [super init];
if (self)
{
self.name = [dict objectForKey:@"name"];
self.sector = [dict objectForKey:@"sector"];
self.activity = [dict objectForKey:@"activity"];
NSDictionary *loactionDictionary = dict[@"location"];
self.country = loactionDictionary[@"country_code"]; //or dict[@"location][@"country_code"];
self.town = loactionDictionary[@"town"];//or dict[@"location][@"town"];
NSDictionary *imageid = dict[@"image"];
self.ImageId = imageid[@"id"];//or dict[@"image][@"id"];
}
return self;
}
我会覆盖description
too:
-(NSString *)description
{
return [NSString stringWithFormat:@"<%@ %p>: name: %@ \n town: %@\n sector: %@\n country: %@\n activity: %@\n image id:", [self class], self, self.name, self.town, self.sector, self.country, self.activity, self.ImageId ];
}
然后在你的代码中:
-(void)addOnlineData:(NSDictionary*)onlineData
{
self.JsonData = onlineData;
NSArray* latestLoans = [self.JsonData objectForKey:@"loans"];
for (NSDictionary *aLoan in latestLoans)
{
NewModelClass *newModelClass = [[NewModelClass alloc] initWithJSONDict:aLoan];
NSLog(@"Loan: %@", loan);
[self.tableData addObject:newModelClass];
}
[[self KivaTableView]reloadData];
}
修改 for 循环,因为您已经知道它是NSDictionary
,所以没有使用for id
, then id
投射到NSDictionary
.
修改方法名称:
以小写开头的方法。
如果您不进行复制,请避免以“复制”开头的命名。
注意:此代码未经测试,可能由于轻微语法错误而无法编译,但您应该了解主要思想。