I have an NSArray
with NSDictionary
and trying to remove duplicate with the following code:
NSDictionary *arnold = @{@"name" : @"arnold", @"state" : @"california"};
NSDictionary *jimmy = @{@"name" : @"jimmy", @"state" : @"new york"};
NSDictionary *henry = @{@"name" : @"henry", @"state" : @"michigan"};
NSDictionary *woz = @{@"name" : @"woz", @"state" : @"california"};
NSArray *people = @[arnold, jimmy, henry, woz];
NSMutableArray *results=[[NSMutableArray alloc]initWithArray: [people valueForKeyPath:@"@distinctUnionOfObjects.state"]];
NSLog(@"results %@", results);
this is the output I get from the nslog:
results (
california,
michigan,
"new york"
)
My question is how to add the full directories to the array?
@distinctUnionOfObjects
will only returns the unique object value specified that property, not the objects themselves.
You may try this:
NSDictionary *arnold = @{@"name" : @"arnold", @"state" : @"california"};
NSDictionary *jimmy = @{@"name" : @"jimmy", @"state" : @"new york"};
NSDictionary *henry = @{@"name" : @"henry", @"state" : @"michigan"};
NSDictionary *woz = @{@"name" : @"woz", @"state" : @"california"};
NSArray *people = @[arnold, jimmy, henry, woz];
NSMutableArray *uniqueArray = [[NSMutableArray alloc] init];
NSMutableSet *checkedStates = [[NSMutableSet alloc] init];
for (NSDictionary *person in people) {
NSString *currentStateName = person[@"state"];
BOOL isDuplicateState = [checkedStates containsObject:currentStateName];
if (!isDuplicateState) {
[uniqueArray addObject:person];
[checkedStates addObject:currentStateName];
}
}
NSLog(@"Results %@", uniqueArray);
The output from NSLog
will be:
Results (
{
name = arnold;
state = california;
},
{
name = jimmy;
state = "new york";
},
{
name = henry;
state = michigan;
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With