2016-11-11 33 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所以請原諒所有語法錯誤。