Search code examples
iosobjective-cxcodensarraynsmutablearray

Add an object to a NSMutableArray using arrayWithObject


This is my code:

NSMutableArray* notifications = [NSMutableArray arrayWithObjects:myObject.dictionary, nil];

After creating the NSMutableArray I do this:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];

How can I add other objects to the NSMutableArray notification?

I know I can do something like:

NSMutableArray* notifications = [NSMutableArray arrayWithObjects:object1.dictionary, object2.dictionary, object3.dictionary, nil];

but I want to add them after the creation of the NSMutableArray.

myObject contains this:

-(NSDictionary *)dictionary {
    return [NSDictionary dictionaryWithObjectsAndKeys:self.name,@"name",self.category,@"category",self.note, @"note",self.dueDate, @"dueDate",self.creationDate, @"creationDate", nil];}

Solution

  • You can add one object as an array to an existing array as follows:

    [notifications addObjectsFromArray: [NSArray arrayWithObject: object.dictionary]];
    

    Alternatively, instead of arrayWithObject, you can also use the literal notation:

    [notifications addObjectsFromArray: @[object.dictionary]];
    

    You can add even more than one object at a time:

    [notifications addObjectsFromArray: @[object1.dictionary, object2.dictionary]];