Dev
Dev

Reputation: 41

NSArray of dictionaries

I have NSArray of NSDictionaries which is coming from server as JSON format. I want to add one more NSDictinoary to the NSarray of NSdictionaries. Nsdictionary is based on key value pair. This is the response which I am getting. I want to add another dictionary of same format into "table". Pls Help..

Thanks in advance..!!

Table =     (
                {
            Name = “xyz”;
            Recordid = 3;
            prefrenceorder = 1;
        },
                {
            Name = “ABC”;
            Recordid = 2;
            prefrenceorder = 2;
        },
                {
            Name = “swe”;
            Recordid = 450;
            prefrenceorder = 3;
        },
                {
            Name = “asd”;
            Recordid = 451;
            prefrenceorder = 4;
        }
    );

Upvotes: 2

Views: 592

Answers (3)

Avt
Avt

Reputation: 17043

It is better not to convert immutable array to a mutable but to use appropriate NSJSONSerialization option - NSJSONReadingMutableContainers

Specifies that arrays and dictionaries are created as mutable objects.

NSMutableArray *mutableArray = [NSJSONSerialization JSONObjectWithData:yourData options:NSJSONReadingMutableContainers error:nil];
[mutableArray addObject:yourNewDictionary];

Upvotes: 0

E-Riddie
E-Riddie

Reputation: 14780

Put the NSDictionary's into a NSMutableArray. And then from your instance add your new object NSDictionary

i.e

//The array which has your NSDictionary objects
NSArray *array;

//Putting this array into mutable one in order to add and delete elements
NSMutableArray *mArray = [array mutableCopy];

//Your custom object that you want to add
NSDictionary *yourObject;

//Add it to the array and voila
[mArray addObject:yourObject];

Upvotes: 1

Tapas Pal
Tapas Pal

Reputation: 7207

As the NSArray coming from server is immutable so you need to create a new instance of NSMutableArray to add your own dictionary with the response coming from server.

NSMutableArray *newTable = [NSMutableArray arrayWithArray:Table];
[newTable addObject:your_new_dictionary];

Upvotes: 1

Related Questions