Filtering an NSArray with custom objects

This question already has an answer here:

  • How do I sort an NSMutableArray with custom objects in it? 25 answers

  • 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.


    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;
    
    链接地址: http://www.djcxy.com/p/70818.html

    上一篇: 排序自定义类

    下一篇: 用自定义对象过滤NSArray