-2
NSMutableArray *arrData =[NSMutableArray array];
arrData =[data objectForKey:@"data"];
NSLog(@"%@",arrData);

NSLog will print like

data = 
(
   {
        date = "2016-01-20";
        "end_time" = "12:25:00";
        "start_time" = "11:00:00";
        "total_units" = 59;
    }
); 

This data comes from server. Now, I want to add one more dictionary of data to this array coming from the server.

I did the following:

NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
[newDict setObject:@"2016-01-22" forKey:@"date"];
[arrData addObject:newDict]; 

Now the app crashed. What went wrong?

[__NSArrayI addObject:]: unrecognized selector sent to instance 0x7fc4d3914d40
Dhara
  • 6,587
  • 2
  • 31
  • 46
Chandrika Visvesh
  • 91
  • 1
  • 1
  • 10

6 Answers6

0
NSMutableArray *arrData =[NSMutableArray array];

Is a method from NSArray class, which create an NSArray instance, not NSMutableArray instance.

What you need is, for example:

NSMutableArray *arrData =[NSMutableArray arrayWithCapacity:0];

Reference: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/index.html#//apple_ref/doc/uid/20000137-SW4

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/#//apple_ref/doc/uid/20000138-SW1

user2829759
  • 3,372
  • 2
  • 29
  • 53
0
NSMutableArray *arrData = [NSMutableArray arrayWithArray:[data objectForKey:@"data"]];

Use the above code instead. Your old code just move the pointer of arrData to [data objectForKey:@"data"]]. It access the same address

Jonny Vu
  • 1,420
  • 2
  • 13
  • 32
0
for (NSDictionary *dict in [data objectForKey:@"data"])
{
    [arrData addObject:dict];
}

now you can add object whwnever you want to add in array

Ashish Ramani
  • 1,214
  • 1
  • 17
  • 30
0

Use:

arrData = [data[@"data"] mutableCopy];

in order to create a mutable copy of the array.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
0

Make sure your array must be mutable. Try allocating your array like this

 NSMutableArray *arrData = [[NSMutableArray alloc] init];

Assign your response object to your arrData like this

NSMutableArray *arrData = [responseDictionary objectForKey:@"data"];

Then do your following stuff and also avoid using new keyword in the start of the variable name.

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                       [dict setObject:@"2016-01-22" forKey:@"date"];
                       [arrData addObject:dict]; 
Shehzad Ali
  • 1,846
  • 10
  • 16
0

You are assigning an NSDictionary object reference to an NSMutableArray object.

arrData =[data objectForKey:@"data"];

Then, when you try to execute addObject method on arrData it crashes because addObject method does not exist for an NSDictionary object.

use :

[arrData addObject:[data objectForKey:@"data"]]
PGDev
  • 23,751
  • 6
  • 34
  • 88