Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data / Cocoa : @distinctUnionOfObjects not returning a usable NSArray*

I have an application that uses Core Data that has a relationship that I would like to group by. I have NSManagedObject classes that were generated by my .xcdatamodel file, and everything seems to be working OK for the most part.

Given a parent / child relationship, I would like to do the following:

A parent has a collection of children. The children have a property, groupByProperty, that I would like to group on.

The following code:

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

produces an NSInvalidArgumentException when trying to set the child pointer.

However, when I do this:

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

everything works fine.

Can anyone explain this behavior? I'm going nuts trying to figure out how this works.

Thanks in advance for any help you can provide...

Chris

like image 719
Chris T. Avatar asked Dec 17 '22 04:12

Chris T.


2 Answers

So, I got my information from this Apple document: Set and Array Operators, where it states "The @distinctUnionOfObjects operator returns an array containing the distinct objects returned by sending valueForKeyPath: to each item in the receiver, passing the key path to the right of the array operator." I assumed that the returned object is an NSArray, because it says "Array", when it should probably say "Array or Set". I changed the returned Object to an NSSet, and then used [[groups allObjects] objectAtIndex:x] to get my object out of there.

It now looks like this:

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

Thanks for your help, I guess I just needed to look at the exception a little bit more carefully, the key here being "-[NSCFSet objectAtIndex:....."

like image 124
Chris T. Avatar answered May 24 '23 20:05

Chris T.


You should do the following:

NSArray *groups = [parent valueForKeyPath:@"@distinctUnionOfObjects.children.groupByProperty"];
Child *child = [groups objectAtIndex:x];
like image 35
Massimo Cafaro Avatar answered May 24 '23 19:05

Massimo Cafaro