使用arrayWithObject将对象添加到NSMutableArray

问题描述

这是我的代码

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

创建NSMutableArray之后,我执行以下操作:

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

如何将其他对象添加到NSMutableArray通知中?

我知道我可以做类似的事情:

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

但是我想在创建NSMutableArray之后添加它们。

myObject包含以下内容

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

解决方法

您可以将一个对象作为数组添加到现有数组,如下所示:

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

或者,您也可以使用文字符号代替arrayWithObject

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

您一次可以添加多个对象:

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