Elton's Blog

Tag: KVC

NSArray 和 KVC

by on 十一.04, 2009, under Mac

Theocoacao有篇不错的介绍NSArray和KVC的文章,我给粗略翻译了一下。

NSArray的-valueForKey: 有一个不是很显著的特性. 你可以使用它返回一个由tree对象包装的值对象的数组。这句话可能不是很容易理解,看下面的例子就清楚了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
NSMutableArray * tree = [NSMutableArray array];
NSDictionary   * p = nil;   // parent
NSDictionary   * c = nil;   // child
NSNumber       * n = nil;   // value
int i;
 
for ( i = 0; i < 10; i++ )
{
n = [NSNumber numberWithInt: i];
c = [NSDictionary dictionaryWithObject:n forKey: @"someKey"];
p = [NSDictionary dictionaryWithObject: c forKey: @"storage"];
[tree addObject: p];
}
 
NSLog (@"%@", tree);
// here's the important part!
NSArray * justValues;
justValues = [tree valueForKeyPath: @"storage.someKey"];
NSLog (@"%@", justValues);

第一个NSLog输出的内容t:

1
2
3
4
5
6
7
8
9
10
11
12
13
NSLog (@"%@", tree);
(
{storage = {someKey = 0; }; },
{storage = {someKey = 1; }; },
{storage = {someKey = 2; }; },
{storage = {someKey = 3; }; },
{storage = {someKey = 4; }; },
{storage = {someKey = 5; }; },
{storage = {someKey = 6; }; },
{storage = {someKey = 7; }; },
{storage = {someKey = 8; }; },
{storage = {someKey = 9; }; }
)

第二个NSLog 返回一个数组的值,这个数组是由封装它的tree对象的 @”storage.someKey”:这个keypath提供的:

1
2
3
4
NSArray * justValues;
justValues = [tree valueForKeyPath: @"storage.someKey"];
NSLog (@"%@", justValues);
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

我发现它真的非常方便,当你使用Core Data要排序一个managed objects对象里面的一个数组的时候。 你可以用一个attribute就把它里面数组的值列出来。.

Leave a Comment :, more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...