Jak przekonwertować NSArray
na NSDictionary
, używając pola int obiektów tablicy jako klucza do NSDictionary
?Konwersja NSArray na NSDictionary
Odpowiedz
- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
id objectInstance;
NSUInteger indexKey = 0U;
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
for (objectInstance in array)
[mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];
return (NSDictionary *)[mutableDictionary autorelease];
}
Dodaje rozszerzenie kategorii do NSArray
. Wymaga trybu C99
(który jest domyślny w tych dniach, ale na wszelki wypadek).
W .h
pliku gdzieś, które mogą być przez cały #import
wyd ..
@interface NSArray (indexKeyedDictionaryExtension)
- (NSDictionary *)indexKeyedDictionary
@end
W pliku .m
..
@implementation NSArray (indexKeyedDictionaryExtension)
- (NSDictionary *)indexKeyedDictionary
{
NSUInteger arrayCount = [self count];
id arrayObjects[arrayCount], objectKeys[arrayCount];
[self getObjects:arrayObjects range:NSMakeRange(0UL, arrayCount)];
for(NSUInteger index = 0UL; index < arrayCount; index++) { objectKeys[index] = [NSNumber numberWithUnsignedInteger:index]; }
return([NSDictionary dictionaryWithObjects:arrayObjects forKeys:objectKeys count:arrayCount]);
}
@end
przykład zastosowanie:
NSArray *array = [NSArray arrayWithObjects:@"zero", @"one", @"two", NULL];
NSDictionary *dictionary = [array indexKeyedDictionary];
NSLog(@"dictionary: %@", dictionary);
Wyjścia:
2009-09-12 08:41:53.128 test[66757:903] dictionary: {
0 = zero;
1 = one;
2 = two;
}
Stworzyłem prostą bibliotekę o nazwie Linq to ObjectiveC, która jest zbiorem metod, które znacznie ułatwiają rozwiązywanie tego typu problemów. W twoim przypadku trzeba metodę Linq-to-ObjectiveC toDictionary, gdzie pole „int” jest określony za pomocą przycisku wyboru:
NSDictionary* dictionary = [sourceArray toDictionaryWithKeySelector:^id(id item) {
return [item intField];
}];
ta zwraca słownika gdzie klawisze są podane przez intField
w tablicy źródłowej.
Spróbuj Magic:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:records
forKeys:[records valueForKey:@"intField"]];
FYI jest to możliwe ze względu na to wbudowana funkcja:
@interface NSArray(NSKeyValueCoding)
/* Return an array containing the results of invoking -valueForKey:
on each of the receiver's elements. The returned array will contain
NSNull elements for each instance of -valueForKey: returning nil.
*/
- (id)valueForKey:(NSString *)key;
To naprawdę magia! Eleganckie i bardzo poręczne rozwiązanie! Tylko jedna uwaga: może lepiej użyć [records valueForKey: @ "otherField"] nie tylko jako rekordy, ponieważ zawiera również "intField". W każdym razie jest to dla mnie nowe, nawet po latach kodowania ... – BootMaker
- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
[array enumerateObjectsUsingBlock:
^(id obj, NSUInteger idx, BOOL *stop){
NSNumber *index = [NSNumber numberWithInteger:idx];
[mutableDictionary setObject:obj forKey:index];
}];
NSDictionary *result = [NSDictionary.alloc initWithDictionary:mutableDictionary];
return result;
}
jest to przykład tworzenia NSMutableDictionary
z listy pracowników NSMutableArray
:
NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:@"saman",@"Ruchira",@"Rukshan",@"ishan",@"Harsha",@"Ghihan",@"Lakmali",@"Dasuni", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];} NSLog(@"dic %@",dict);
Uwielbiam używać kategorii, więc preferowałbym to rozwiązanie zamiast używać prostej funkcji ze względu na sposób wywoływania go bezpośrednio na obiekcie, tak jakby zawsze znał tę metodę. – Woofy