我必须创建像这样的数组:
photos:[
{
"name":"20130201064350_01.jpg",
"quantity":"2"
},
{
"name":"20130201064350_02.jpg",
"quantity":"1"
}
]
在这里,我有name
数组和Quantity
数组。
如何创建这种类型的数组或字典?
使用新语法,这很简单:
NSArray *photos = @[
@{
@"name":@"20130201064350_01.jpg",
@"quantity":@"2"
},
@{
@"name":@"20130201064350_02.jpg",
@"quantity":@"1"
}
];
(即几乎只是@
在您的问题中放在结构前面)。
NSArray *array = @[ @{ "name":"20130201064350_01.jpg", "quantity":"2" }, @{"name":"20130201064350_02.jpg", "quantity":"1"} ];
//These are new literals
它是一个数组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];
如果Quantity
和name
数组的计数相等。使用一个数组中的任何一个运行 for 循环并将其NSDictionary
添加并将该字典添加到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);