Skip to content

Instantly share code, notes, and snippets.

@cremaschi
Created November 12, 2013 01:51
Show Gist options
  • Save cremaschi/7424044 to your computer and use it in GitHub Desktop.
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.
//
// 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
//
// 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
@benvium
Copy link

benvium commented Jun 30, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment