2016-11-11 61 views
0

我需要使用NSDictionary发送数据到服务器。数据将是名称,性别dll,来自文本字段。我知道我可以保存一本这样的字典。Objective-C附加字典到NSDictionary

NSDictionary * = @{@"employee": @"EmpA", 
          @"gender":@"Male", 
          @"pob":@"SF", 
          @"age":@"27", 
          }; 

但我需要添加多个数据,因为我有按钮,可以重复窗体过程。之后,我会根据下面的格式将整个数据发送到服务器。

"employee": [{ 
    "name": "EmpA", 
    "gender": "Male", 
    "pob": "SF", 
    "age": 27 
    }, { 
    "name": "EmpB", 
    "gender": "Female", 
    "pob": "TX", 
    "age": 36 
    }] 

我如何动态追加字典?

感谢

+4

使用'NSMutableArray'来保存多个字典 – rckoenes

+0

,因为rckoenes已经表示您需要使用Mutable版本。总的来说你会使用'NSMutableArray','NSMutableDictionary','NSMutableString','NSMutableRequest'等等很多 – Honey

回答

0

您需要创建词典的数组,并在你的“员工”键插入。像这样的东西应该工作:

NSMutableDictionary *employee = [[NSMutableDictionary alloc]init]; 
NSMutableDictionary *emplyeeA = [@{@"name": @"EmpA", @"gender": @"Male", @"pob": @"SF", @"age": @"27"} mutableCopy]; 
NSMutableDictionary *emplyeeB = [@{@"name": @"EmpB", @"gender": @"Female", @"pob": @"TX", @"age": @"36"} mutableCopy]; 
NSMutableArray *tempArray = [[NSMutableArray alloc] init]; 
[tempArray addObject: emplyeeA]; 
[tempArray addObject: emplyeeB]; 
[employee setObject:tempArray forKey:@"employee"]; 
+1

你不需要请求mutableCopy for emplyeeA&B –

1

使用词典的数组:

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

for(//loop through the forms) { 
    NSDictionary *emp = @{@"name": @"EmpA", 
         @"gender":@"Male", 
         @"pob":@"SF", 
         @"age":@"27", 
         }; 
    [employees addObject:emp]; 
} 

NSDictionary *payload = @{@"employee": employees}; 

我不手边有一个MAC所以请原谅所有语法错误。