核心数据/可可:@distinctUnionOfObjects没有返回可用的NSArray*

Chr*_* T. 4 iphone cocoa cocoa-touch core-data objective-c

我有一个使用Core Data的应用程序,它具有我想要分组的关系.我有我的.xcdatamodel文件生成的NSManagedObject类,并且大部分内容似乎都正常.

鉴于父/子关系,我想做以下事情:

父母有一个孩子的集合.孩子们有一个属性,groupByProperty,我想分组.

以下代码:

NSSet *allChildren = parent.children;
NSArray *groups = [allChildren valueForKeyPath:@"@distinctUnionOfObjects.groupByProperty"];
Child *child = [groups objectAtIndex:x]; //x is the row that I would like to retrieve
Run Code Online (Sandbox Code Playgroud)

尝试设置子指针时产生NSInvalidArgumentException.

但是,当我这样做时:

NSSet *allChildren = parent.children;
NSArray *groups = [[NSArray alloc] initWithArray:[allChildren valueForKeyPath:@"@distinctUnionOfObjects.groupByProperty"]];
Child *child = [groups objectAtIndex:x]; //x is the row that I would like to retrieve
Run Code Online (Sandbox Code Playgroud)

一切正常.

谁能解释这种行为?我很想弄清楚它是如何工作的.

提前感谢您提供的任何帮助......

克里斯

Chr*_* T. 9

所以,我从这个Apple文档得到了我的信息:Set和Array Operators,它声明" @distinctUnionOfObjects运算符返回一个数组,其中包含通过发送valueForKeyPath:返回给接收器中每个项目返回的不同对象,将键路径传递给右边数组运算符." 我假设返回的对象是一个NSArray,因为它说"Array",它应该说"Array或Set".我将返回的Object更改为NSSet,然后使用[[groups allObjects] objectAtIndex:x]将我的对象从那里取出.

它现在看起来像这样:

NSSet *allChildren = parent.children;
NSSet *groups = [allChildren valueForKeyPath:@"@distinctUnionOfObjects.groupByProperty"];
Child *child = [[groups allObjects] objectAtIndex:x]; //x is the row that I would like to retrieve
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助,我想我只需要更仔细地查看异常,这里的关键是" - [ NSCFSet objectAtIndex:....."