Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios distinctUnionOfObjects is not returning all the content of dictionaries

Tags:

ios

nsarray

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?

like image 260
HelenaM Avatar asked Oct 21 '22 06:10

HelenaM


1 Answers

@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;
    }
)
like image 78
Douglas Ferreira Avatar answered Nov 15 '22 10:11

Douglas Ferreira