So *_* It 0 objective-c nsdictionary nsarray kvc
目标:使用优雅代码获取包含给定NSDictionary的唯一键的NSArray
带当前工作解决方案的示例代码
NSArray *data = [[NSArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"a", [NSNumber numberWithInt:2], @"b", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:3], @"b", [NSNumber numberWithInt:4], @"c", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:6], @"c", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:7], @"b", [NSNumber numberWithInt:8], @"a", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:8], @"c", [NSNumber numberWithInt:9], @"b", nil],
nil];
// create an NSArray of all the dictionary keys within the NSArray *data
NSMutableSet *setKeys = [[NSMutableSet alloc] init];
for (int i=0; i<[data count]; i++) {
[setKeys addObjectsFromArray:[[data objectAtIndex:i] allKeys]];
}
NSArray *arrayKeys = [setKeys allObjects];
NSLog(@"arrayKeys: %@", arrayKeys);
Run Code Online (Sandbox Code Playgroud)
返回所需的键数组:
2012-06-11 16:52:57.351 test.kvc[6497:403] arrayKeys: (
a,
b,
c
)
Run Code Online (Sandbox Code Playgroud)
问题:是否有更优雅的方式来接近这个?当然必须有一些KVC方法可以获得所有的密钥,而无需遍历数组?我一直在看Apple Developer Documentation,看不到解决方案.有任何想法吗?(看纯粹优雅的代码而不是表现).
通常你可以通过做这样的事情来使用KVC:
NSArray *uniqueKeys = [data valueForKeyPath:@"@distinctUnionOfArrays.allKeys";
Run Code Online (Sandbox Code Playgroud)
但是NSDictionary会覆盖valueForKey:KVC内部使用的选择器,因此无法正常工作.
NSDictionary valueForKey:方法的文档告诉我们:
如果key不以"@"开头,则调用objectForKey:.如果key以"@"开头,则删除"@"并使用其余键调用[super valueForKey:].
所以我们只需@在allKeys之前插入一个:
NSArray *uniqueKeys = [data valueForKeyPath:@"@distinctUnionOfArrays.@allKeys"];
Run Code Online (Sandbox Code Playgroud)
我们得到了我们想要的东西:
(lldb) po [data valueForKeyPath:@"@distinctUnionOfArrays.@allKeys"]
(id) $14 = 0x07bb2fc0 <__NSArrayI 0x7bb2fc0>(
c,
a,
b
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1254 次 |
| 最近记录: |