0
votes

I have an NSArray of custom objects. Consider that the custom objects have a PageNumber property. I would like to filter my NSArray with a condition like "customObject.PageNumber is distinct".

I know I can loop through the array and eliminate object with duplicate pageNumbers. But is there any easy way to do it? I have tried,

[myarray valueForKeyPath:@"distinctUnionOfObjects.pageNumber"];

It is giving me the unique page numbers (like 7, 8, 9). But I want the custom object itself rather than just page numbers. Can any predicate help me?

2

2 Answers

1
votes

I have created a simple library, called Linq to ObjectiveC, which is a collection of methods that makes this kind of problem much easier to solve. In your case you need the Linq-to-ObjectiveC distinct method:

NSArray* itemsWithUniquePageNumbers = [items distinct:^id(id item) {
    return [item pageNumber];
}];

This returns an array of objects, each one with a unique page number.

0
votes

Yes, that is possible with the help of NSPredicate

customObject=[(NSArray*)[myArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.PageNumber==%d",pageNumber]] lastObject];
//pageNumber is an integer

The filtered array is an NSArray of your custom objects which is the result of filtering using the predicate. Since your page number is unique, it will return only an array of one object. We get that by passing lastObject message to it.

Refer: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/predicates.html#//apple_ref/doc/uid/TP40001798-SW1