joh*_*hnl 45 iphone objective-c nsdictionary nsarray
我怎么能转换的NSArray一种NSDictionary,通过阵列的对象的一个int领域作为重点NSDictionary?
mal*_*hal 76
试试这个魔法:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:records
forKeys:[records valueForKey:@"intField"]];
Run Code Online (Sandbox Code Playgroud)
仅供参考,因为这个内置功能:
@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;
Run Code Online (Sandbox Code Playgroud)
Ale*_*lds 53
- (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];
}
Run Code Online (Sandbox Code Playgroud)
这会添加类别扩展名NSArray.需要C99模式(这是默认情况,但以防万一).
在一个.h可以#import由所有人编辑的文件中..
@interface NSArray (indexKeyedDictionaryExtension)
- (NSDictionary *)indexKeyedDictionary
@end
Run Code Online (Sandbox Code Playgroud)
在一个.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
Run Code Online (Sandbox Code Playgroud)
使用示例:
NSArray *array = [NSArray arrayWithObjects:@"zero", @"one", @"two", NULL];
NSDictionary *dictionary = [array indexKeyedDictionary];
NSLog(@"dictionary: %@", dictionary);
Run Code Online (Sandbox Code Playgroud)
输出:
2009-09-12 08:41:53.128 test[66757:903] dictionary: {
0 = zero;
1 = one;
2 = two;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61619 次 |
| 最近记录: |