我有一个NSMutableArray,它包含几个NSMutableDictionary对象,每个dict都有一个NSString和一个NSMutableArray。
我的问题是我需要根据字符串匹配找到正确的dict,当找到将对象插入到找到字符串匹配的同一个dict中的NSMutableArray时,我只能在第一次执行此工作时数组为空,因为之后我无法匹配正确的字符串:
这是我到目前为止尝试过的,我尝试使用包含对象,但是不会让我进入数组内的dict,所以我被卡住了
NSMutableArray *variantOptions = [[NSMutableArray alloc] init];
for (NSDictionary *variant in variantInfo) {
NSMutableDictionary *variantOption = [[NSMutableDictionary alloc] init];
NSMutableArray *variantOptionValues = [[NSMutableArray alloc] init];
NSString *name = variant[@"name"];
NSString *value = variant[@"value"];
if(variantOptions.count > 0) {
// Need to loop through the array until name isEquaToString variantOptionName and when true insert value into variantOptionValuesArray in that same dict and if not exists create a new dict and insert in array
} else {
[variantOptionValues addObject:value];
[variantOption setObject:name forKey:@"variantOptionName"];
[variantOption setObject:variantOptionValues forKey:@"variantOptionValues"];
}
[variantOptions addObject:variantOption];
}
答案 0 :(得分:-1)
for (NSDictionary *variant in variantInfo) {
NSString *name = variant[@"name"];
NSString *value = variant[@"value"];
BOOL found = false;
for (NSMutableDictionary *v in variantOptions) {
if (v[@"name"] isequalToString:name]) {
NSMutableArray *values = v[@"variantOptionValues"];
[values addObject:value];
found = true;
break;
}
}
if (!found) {
// name was not found
NSMutableDictionary *variantOption = [[NSMutableDictionary alloc] init];
NSMutableArray *variantOptionValues = [NSMutableArray alloc] init];
[variantOptionValues addObject:value];
[variantOption setObject:name forKey:@"variantOptionName"];
[variantOption setObject:variantOptionValues forKey:@"variantOptionValues"];
[variantOptions addObject:variantOption];
}
}