Created
November 12, 2013 01:51
-
-
Save cremaschi/7424044 to your computer and use it in GitHub Desktop.
A category on the NSPredicate to add the distinct function.
You can easily create a predicate that removes duplicates in an array just passing the property name you want to check.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSPredicate+Distinct.h | |
// | |
// Created by Maurizio Cremaschi on 11/11/2013. | |
// Copyright (c) 2013 Myfleek Ltd. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSPredicate (Distinct) | |
+ (NSPredicate *)predicateForDistinctWithProperty:(NSString *)property; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSPredicate+Distinct.m | |
// | |
// Created by Maurizio Cremaschi on 11/11/2013. | |
// Copyright (c) 2013 Myfleek Ltd. All rights reserved. | |
// | |
#import "NSPredicate+Distinct.h" | |
@implementation NSPredicate (Distinct) | |
+ (NSPredicate *)predicateForDistinctWithProperty:(NSString *)property | |
{ | |
__block NSMutableSet *set = [NSMutableSet new]; | |
return [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) { | |
id key = [evaluatedObject valueForKeyPath:property]; | |
BOOL contained = [set containsObject:key]; | |
if (!contained) { | |
[set addObject:key]; | |
} | |
return !contained; | |
}]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks great, but it's worth nothing this can't be used with Core Data - fails with
Problem with subpredicate BLOCKPREDICATE(0x7ff07af699a0)
See here: http://stackoverflow.com/questions/3543208/nsfetchrequest-and-predicatewithblock