I have an NSArray of NewsArticle objects:
@interface NewsArticle : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSDate *dateTime;
@property (nonatomic, strong) NSString *content;
@end
And I want to create an NSArray of the unique dates (ignoring time) stored within each article.dateTime – I know I can do this the long way around by enumerating the array and doing the checking myself, but I’m hoping for a simpler solution.
I’m from a C# background and I know in C# I could do this with a simple LINQ statement – it would seem that NSPredicate might offer this functionality, but I can’t work out how, or find any suitable examples online.
NSPredicateis designed for filtering a collection of objects, but you want to extract a property from each member of the collection.You can (as CAMOBAP said in his comment) use key-value coding (KVC) to get an array of all the
dateTimevalues. Then you can use anNSSetto eliminate the duplicates:You can even do it all in one KVC message, using the somewhat esoteric
@distinctUnionOfObjectskey:Note that this second example uses
valueForKeyPath:, notvalueForKey:.You can learn more (oh so much more!) by reading the Key-Value Coding Programming Guide.