Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Duplicate Objects From NSMutableArray object property? [duplicate]

I have one NSObject with properties as following

@property (nonatomic, retain) NSString * destinationid;
@property (nonatomic, retain) NSString * destinationname;
@property (nonatomic, retain) NSString * assetid;
@property (nonatomic, retain) NSString * assetname;
@property (nonatomic, retain) NSString * assetdescription;

Here, I save this in NSMutableArray.

The data which I get from server contains same DestinationName, but different other properties.

I want to check, if same name of Object is already added to NSMutableArray, don't add it again.

I tried to user innner loops but no use :(

Thanks

like image 555
Duaan Avatar asked Dec 03 '22 21:12

Duaan


2 Answers

Here's one solution:

NSArray *originalArray = ... // original array of objects with duplicates
NSMutableArray *uniqueArray = [NSMutableArray array];
NSMutableSet *names = [NSMutableSet set];
for (id obj in originalArray) {
    NSString *destinationName = [obj destinationname];
    if (![names containsObject:destinationName]) {
        [uniqueArray addObject:obj];
        [names addObject:destinationName];
    }
}
like image 153
rmaddy Avatar answered Dec 28 '22 23:12

rmaddy


One way to do it is to create a new array that only contains the destination names from your other array, and check if the name from your server is contained there:

NSArray *names = [self.mut valueForKey:@"destinationname"];
    if (![names containsObject:destName]) {
        [self.mut addObject:newObjectFromServer];
    }

mut is the name of my mutable array, and destName is the destination name in the object your getting from the server.

like image 32
rdelmar Avatar answered Dec 28 '22 22:12

rdelmar