2009-09-12 35 views

Trả lời

51
- (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]; 
} 
9

Điều này thêm tiện ích mở rộng danh mục vào NSArray. Cần chế độ C99 (mặc định là những ngày này, nhưng chỉ trong trường hợp).

Trong một tập tin .h đâu đó rằng có thể #import ed bởi tất cả ..

@interface NSArray (indexKeyedDictionaryExtension) 
- (NSDictionary *)indexKeyedDictionary 
@end 

Trong một tập tin .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 

Ví dụ sử dụng:

NSArray *array = [NSArray arrayWithObjects:@"zero", @"one", @"two", NULL]; 
NSDictionary *dictionary = [array indexKeyedDictionary]; 

NSLog(@"dictionary: %@", dictionary); 

Đầu ra:

2009-09-12 08:41:53.128 test[66757:903] dictionary: { 
    0 = zero; 
    1 = one; 
    2 = two; 
} 
+1

Tôi thích sử dụng các loại, vì vậy tôi sẽ sử dụng giải pháp này thay vì sử dụng một hàm đơn giản vì cách gọi trực tiếp trên đối tượng, như thể nó luôn biết phương thức đó. – Woofy

-2

Tôi đã tạo một thư viện đơn giản, được gọi là Linq to ObjectiveC, là tập hợp các phương pháp giúp loại sự cố này dễ giải quyết hơn nhiều. Trong trường hợp của bạn, bạn cần phương pháp Linq-to-ObjectiveC toDictionary, nơi trường 'int' của bạn được xác định thông qua một bộ chọn chính:

NSDictionary* dictionary = [sourceArray toDictionaryWithKeySelector:^id(id item) { 
    return [item intField]; 
}]; 

này trả về một từ điển, nơi các phím được đưa ra bởi các intField trong mảng nguồn.

71

Hãy thử kỳ diệu này:

NSDictionary *dict = [NSDictionary dictionaryWithObjects:records 
            forKeys:[records valueForKey:@"intField"]]; 

FYI này là có thể vì điều này tích hợp tính năng:

@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; 
+0

Nó thực sự là một phép thuật! Giải pháp thanh lịch và thực sự tiện dụng! Chỉ cần một lưu ý: Có thể tốt hơn để sử dụng [records valueForKey: @ "otherField"] không chỉ là bản ghi, vì nó sẽ chứa "intField" quá. Dù sao nó mới cho tôi ngay cả sau nhiều năm mã hóa ... – BootMaker

1
- (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; 
} 
2

Đây là một ví dụ về việc tạo ra một NSMutableDictionary từ danh sách nhân viên 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); 
Các vấn đề liên quan