NSArray: Remove objects with duplicate properties

前端 未结 5 1818
迷失自我
迷失自我 2020-12-15 10:12

I have an NSMutableArray that contains a few custom objects. Two of the objects have the same properties such as title and author. I want to remove the duplicate object an

5条回答
  •  天命终不由人
    2020-12-15 10:19

    You can use the uniqueness of an NSSet to get distinct items from your original array. If you have the source code for Assest you will need to override the hash and isEqual: method on the Asset class.

    @interface Asset : NSObject
    @property(copy) NSString *title, *author;
    @end
    
    @implementation Asset
    @synthesize title, author;
    
    -(NSUInteger)hash
    {
        NSUInteger prime = 31;
        NSUInteger result = 1;
    
        result = prime * result + [self.title hash];
        result = prime * result + [self.author hash];
    
        return result;
    }
    
    -(BOOL)isEqual:(id)object
    {
        return [self.title isEqualToString:[object title]] && 
        [self.author isEqualToString:[object author]];
    }
    
    - (void)dealloc {
        [title release];
        [author release];
        [super dealloc];
    }
    
    @end
    

    Then to implement:

    Asset *asset;
    NSMutableArray *items = [[[NSMutableArray alloc] init] autorelease];
    
    // First
    asset = [[Asset alloc] init];
    asset.title = @"Developer";
    asset.author = @"John Smith";
    [items addObject:asset];
    [asset release];
    
    // Second
    asset = [[Asset alloc] init];
    asset.title = @"Writer";
    asset.author = @"Steve Johnson";
    [items addObject:asset];
    [asset release];
    
    // Third
    asset = [[Asset alloc] init];
    asset.title = @"Developer";
    asset.author = @"John Smith";
    [items addObject:asset];
    [asset release];
    
    NSLog(@"Items: %@", items);
    
    NSSet *distinctItems = [NSSet setWithArray:items];
    
    NSLog(@"Distinct: %@", distinctItems);
    

    And if you need an array at the end you can just call [distinctItems allObjects]

提交回复
热议问题