2013-02-26 133 views
-4

我要創建陣列,如:NSArray的使用對象IOS

photos:[ 
     { 
     "name":"20130201064350_01.jpg", 
     "quantity":"2" 
     }, 
     { 
     "name":"20130201064350_02.jpg", 
     "quantity":"1" 
     } 
    ] 

在這裏,我有name陣列和陣列Quantity

我如何創建這種類型的數組或字典的?

+0

是不是JSON符號系統?如果是的話,應該使用SBJSon來解析這種類型的數據。 – 2013-02-26 14:31:51

回答

0

這是aarray的NSMutableDictionary

NSMutableDictionary *dic1 = [[NSMutableDictionary alloc] init]; 
[dic1 setValue:@"20130201064350_01.jpg" forKey:@"name"]; 
[dic1 setValue:@"2" forKey:@"quantity"]; 

NSMutableDictionary *dicn = [[NSMutableDictionary alloc] init]; 
[dicn setValue:@"n.jpg" forKey:@"name"]; 
[dicn setValue:@"n" forKey:@"quantity"]; 

//並以NSArray的

NSArray *myArray = [NSArray arrayWithObject:dic1, dic2, ........dicn, nil]; 
+2

'的setValue:forKey:'是不是NSDictionary'的'一部分,但'NSMutableDictionary' – Martin 2013-02-26 07:38:43

+0

@上martin-燁...üR右了我的錯誤..感謝很多關於通知我:) – iPatel 2013-02-26 07:46:42

-1

檢查:

NSArray

NSDictionary

例如:

NSDictionary * d1 = [NSDictionary dictionaryWithObjectAndKeys:@"20130201064350_01.jpg", @"name", [NSNumber numberWithInt:2], @"quantity", nil]; 

NSArray * a = [NSArray arrayWithObjects:d1, d2, d3, ..., nil]; 
+0

您的DIC的鍵和值是錯誤的命令。這應該是這樣的[NSDictionary的dictionaryWithObjectAndKeys:@ 「20130201064350_01.jpg」,@ 「姓名」,[NSNumber的numberWithInt:2],@ 「量」,零]。 – 2013-02-26 07:29:06

+0

哎呀,編輯... – Martin 2013-02-26 07:35:40

0

使用新的語法,這簡直是:

NSArray *photos = @[ 
     @{ 
     @"name":@"20130201064350_01.jpg", 
     @"quantity":@"2" 
     }, 
     @{ 
     @"name":@"20130201064350_02.jpg", 
     @"quantity":@"1" 
     } 
    ]; 

(即非常簡單,只是把@結構的前面,你的問題)。

0
NSArray *array = @[ @{ "name":"20130201064350_01.jpg", "quantity":"2" }, @{"name":"20130201064350_02.jpg", "quantity":"1"} ]; 
//These are new literals 
0

如果同時Quantityname數組相等,則計數。運行一個用於與任何一個陣列的循環,並將其添加上NSDictionary並添加到dicitonary NSMutableArray

例如:

quantityArray = [NSArray arrayWithObjects:quantity1, quantity2, quantity3, ..., nil]; 

namesArray = [NSArray arrayWithObjects:name1, name2, name3, ..., nil]; 

NSMutableArray *mainArray = [[NSMUtableArray alloc] init]; 

for (int i = 0; i < [namesArray count]; i++) { 

NSDictionary* dicitonary = [NSDictionary dictionaryWithObjectAndKeys:[namesArray objectAtIndex:i], [quantityArray objectAtIndex:i], nil]; 
    [mainArray addObject:dicitonary]; 
} 

NSLog(@"mainArray = %@", mainArray);