1

I have a class like this :

@interface MyObject : NSObject 
@property (nonatomic, strong) NSString *type;
@end

and I am creating an array like this:

NSMutableArray *array = [NSMutableArray array];
MyObject *obj = [[MyObject alloc] init];
obj.type = @"test1";
[array addObject:obj];

MyObject *obj2 = [[MyObject alloc] init];
obj2.type = @"test2";
[array addObject:obj2];

MyObject *obj3 = [[MyObject alloc] init];
obj3.type = @"test1";
[array addObject:obj3];

I would like to filter the array to just have only the objects which have different types, in my example just to have obj1, obj2 and remove the obj3.

Guillaume Algis
  • 10,000
  • 5
  • 39
  • 68
samir
  • 4,316
  • 6
  • 44
  • 75

2 Answers2

4

Something along these lines should do the trick:

NSMutableSet * types = [NSMutableSet setWithCapacity:10];
NSPredicate * filterPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {

    if ([types containsObject:[evaluatedObject type]]) {
        return NO;
    }
    else {
        [types addObject:[evaluatedObject type]];
        return YES
    }
}];
NSArray * filteredArray = [detailedError filteredArrayUsingPredicate:filterPredicate];

The above code keeps the first object of each type and removes others.

Engin Kurutepe
  • 6,604
  • 3
  • 32
  • 63
2

I would do this by just overriding hash and isEqual:

- (BOOL) isEqual:(id)object
{
    if([object isKindOfClass: [self class]])
        return [_type isEqualToString: object];
    return NO;
}

- (NSInteger) hash
{
    return [_type hash];
}

Then taking the distinct objects array from a set created from the array:

NSArray* filteredArray= [NSSet setWithArray: array].allObjects;
Ramy Al Zuhouri
  • 20,942
  • 23
  • 94
  • 176
  • Even though this is very elegant solution for this problem, I think it might have side effects if the OP needs to use isEqual: somewhere else, maybe obj1.type == obj2.type does not always necessitate obj1==obj2 – Engin Kurutepe Jul 04 '13 at 14:56
  • This is intended to be used on a class like OP's *MyObject*, which has only *type* and no other properties. – Ramy Al Zuhouri Jul 04 '13 at 15:04