nsarray 轉 nsdictionary

將包有 dictionary 的 nsarray 轉成 dictionary , key 為高亮的那一行。


- (NSMutableDictionary *)indexKeyedDictionaryFromArray:(NSArray *)array
{
id objectInstance;

NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
for (objectInstance in array) {

[mutableDictionary setObject:objectInstance forKey:[NSString stringWithFormat:@"%@", [objectInstance objectForKey:@"name"]]];

}
return (NSMutableDictionary *)mutableDictionary;
}

使用範例


NSArray *array = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"mark", @"name", @"100", @"score", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"tom", @"name", @"78", @"score", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"mary", @"name", @"81", @"score", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"sandy", @"name", @"65", @"score", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"sam", @"name", @"98", @"score", nil],
nil];

NSDictionary *dictionary = [self indexKeyedDictionaryFromArray:array];

發表迴響