Can i write last three lines of code in a single line:
NSArray* latestLoans = [self.JsonData objectForKey:@\"loans\"];
for (id object in latestLoans) {
NSDiction
Heres what I would do:
create a custom init for NewModelClass in order to remove it from this part of code. That way, if you have to create a new object of NewModelClass, you won't have to rewrite all the lines.
In NewModelClass.h:
-(id)initWithJSONDict:(NSDictionary *)dict;
In NewModelClass.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;
}
I'd override 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 ];
}
Then in your code:
-(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];
}
Modification of the for loop, since you already know it's a NSDictionary, so no use of for id, then id cast to NSDictionary.
Modification of the method name:
Start method with a lower case.
Avoid naming starting with "copy" if you don't do a copy.
Note: This code is not tested, it may not compile due to a light syntax error, but you should get the main idea.