Tajuddin Tajuddin - 3 months ago 14
Objective-C Question

NSDictionary to NSMutableArray

Here is my API response -

{"kitchen":"3","bath":"5","lanundry":"0","dining":"0","bedroom":"0"}


I have loaded this in
NSDictionary
and I can retrieve the value using key like -

NSDictionary *pdata = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil];
[pdata objectForKey:@"dining"]


I want add the
dictionary
object into
NSMutableArray
but it overrides the all the array values with the last one even though it adds five records.

itemsA=[[NSMutableArray alloc] init];


imgCount *img=[[imgCount alloc] init];

if([pdata objectForKey:@"kitchen"])
{

[img setCount:[pdata objectForKey:@"kitchen"]];
[img setDesc:@"Kitchen"];

[itemsA addObject:img];
}
if([pdata objectForKey:@"bath"])
{
[img setCount:[pdata objectForKey:@"bath"]];
[img setDesc:@"Bathroom"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"lanundry"])
{
[img setCount:[pdata objectForKey:@"lanundry"]];
[img setDesc:@"Laundry"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"dining"])
{
[img setCount:[pdata objectForKey:@"kitchen"]];
[img setDesc:@"Kitchen"];
[itemsA addObject:img];
}
if([pdata objectForKey:@"bedroom"])
{
[img setCount:[pdata objectForKey:@"bedroom"]];
[img setDesc:@"Bedroom"];
[itemsA addObject:img];
}


My table view shows 5 rows with the last value -

Bedroom (0)


But i want result like this

{"desc":"bathroom","count":"0"}, {"desc":"dining","count":"3"}

Answer

The problem with your code is you are creating only one img object and re-using it. Since all objects are accessed by reference in Objective-C, you need to create separate img objects in all if conditions. Try this

itemsA=[[NSMutableArray alloc] init];

 if([pdata objectForKey:@"kitchen"])
    {
       imgCount *img=[[imgCount alloc] init];
       [img setCount:[pdata objectForKey:@"kitchen"]];
       [img setDesc:@"Kitchen"];

       [itemsA addObject:img];
    }
 if([pdata objectForKey:@"bath"])
    {
       imgCount *img=[[imgCount alloc] init];
       [img setCount:[pdata objectForKey:@"bath"]];
       [img setDesc:@"Bathroom"];
       [itemsA addObject:img];
     }
 if([pdata objectForKey:@"lanundry"])
     {
        imgCount *img=[[imgCount alloc] init];
        [img setCount:[pdata objectForKey:@"lanundry"]];
        [img setDesc:@"Laundry"];
        [itemsA addObject:img];
      }
 if([pdata objectForKey:@"dining"])
      {
         imgCount *img=[[imgCount alloc] init];
         [img setCount:[pdata objectForKey:@"kitchen"]];
         [img setDesc:@"Kitchen"];
         [itemsA addObject:img];
       }
  if([pdata objectForKey:@"bedroom"])
      {
        imgCount *img=[[imgCount alloc] init];
        [img setCount:[pdata objectForKey:@"bedroom"]];
        [img setDesc:@"Bedroom"];
        [itemsA addObject:img];
      }
Comments