Alternate Syntax fo assigning json data objectForKey to attributes of class

前端 未结 1 1522
北荒
北荒 2021-01-29 08:27

Can i write last three lines of code in a single line:

NSArray* latestLoans = [self.JsonData objectForKey:@\"loans\"];
for (id object in latestLoans) {
NSDiction         


        
1条回答
  •  情书的邮戳
    2021-01-29 08:51

    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.

    0 讨论(0)
提交回复
热议问题