2

I am stuck in one problem.I am not able to get full object from an array.I have array of class objects and i need to get list of unique elements.i write this code

[objects valueForKeyPath:@"@distinctUnionOfObjects.B1_UM"]

But the problem is my class have many elements and i get list of only unique B1_UM,instead i need list of objects where B1_UM is unique

1
  • Get the array, put it into NSSet. Commented Nov 28, 2013 at 13:30

1 Answer 1

1

I think you have to do that "manually" by enumerating over all objects, and using a set to keep track of which keys have already been added. Something like this (untested):

NSMutableSet *b1ums = [NSMutableSet set];
NSMutableArray *uniqueObjects = [NSMutableArray array];
for (MyClass *obj in objects) {
   if (![b1ums containsObject:obj.b1_um]) {
       [b1ums addObject:obj.b1_um];    // remember key
       [uniqueObjects addObject:obj];  // add object
   }
}

Theoretically, you could override isEqual and hash in your custom class to consider two objects identical if the b1_um property is equal. But that might be a bit overkill.

Edit: I had not noticed that your question is tagged with [core-data]. For managed objects, an alternative approach would be possible: Execute a fetch request with NSDictionaryResultType and set propertiesToGroupBy to the "b1_um" attribute. Then you can pick one object from each group in the returned result.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.