Karuppu MGR Karuppu MGR - 5 months ago 8
iOS Question

Efficiently looping the jsonarray containing month and date that are of optional values

I have got the following json array. I want to concatenate statutory month (in terms of words )and add them into data base.
Sometimes months and date may not be present. Sometimes date will be present and months wont be present and vice versa. I have to handle this conditions and make store the date and month like 31 January,30April etc into the db.

[
{
"statutory_month": 1,
"statutory_date": 31
},
{
"statutory_month": 4,
"statutory_date": 30
},
{
"statutory_month": 7,
"statutory_date": 31
},
{
"statutory_month": 10,
"statutory_date": 31
}
]


Is there an efficient way to handle this situation without doing lots of loops?

Answer

Have you try this first create one months array. After that extract data from dictionary like this

NSArray *months = [[NSArray alloc] initWithObjects:@"Jan", @"Feb", @"Mar", @"Apr", @"May", @"Jun", @"July", @"Aug", @"Sept", @"Oct", @"Nov", @"Dec", nil];
NSArray *resultDate = [[NSArray alloc] init];
for (NSDictionary *dic in jsonArr) //jsonArr is your response arr
{
     if([dic objectForKey:"statutory_month"] && [dic objectForKey:"statutory_date"]) {
         NSString *dateObj = [NSString stringWithFormat:@"%d %@",[dic objectForKey:@"statutory_date"], [months objectAtIndex:[dic objectForKey:"statutory_month"]]];
     }
     else if([dic objectForKey:"statutory_date"]) {
         NSString *dateObj = [NSString stringWithFormat:@"%d",[dic objectForKey:@"statutory_date"]];
     }
     else if([dic objectForKey:"statutory_month"]) {
         NSString *dateObj = [NSString stringWithFormat:@"%@",[months objectAtIndex:[dic objectForKey:"statutory_month"]]];
     }
     else {
         NSString *dateObj = @"No date";
     }
     [resultDate addObject:dateObj];
}

Hope this will help you.

Comments