iPhone - getting unique values from NSArray object

前端 未结 2 1465
名媛妹妹
名媛妹妹 2020-12-07 08:51

I have an NSArray formed with objects of a custom class. The class has 3 (city, state, zip) string properties. I would like to get all unique state values from

2条回答
  •  粉色の甜心
    2020-12-07 09:06

    Take a look at keypaths. They are super powerful and I use them instead of NSPredicate classes most of the time. Here is how you would use them in your example...

    NSArray *uniqueStates;
    uniqueStates = [customObjects valueForKeyPath:@"@distinctUnionOfObjects.state"];
    

    Note the use of valueForKeyPath instead of valueForKey.

    Here is a more detailed/contrived example...

    NSDictionary *arnold = [NSDictionary dictionaryWithObjectsAndKeys:@"arnold", @"name", @"california", @"state", nil];
    NSDictionary *jimmy = [NSDictionary dictionaryWithObjectsAndKeys:@"jimmy", @"name", @"new york", @"state", nil];
    NSDictionary *henry = [NSDictionary dictionaryWithObjectsAndKeys:@"henry", @"name", @"michigan", @"state", nil];
    NSDictionary *woz = [NSDictionary dictionaryWithObjectsAndKeys:@"woz", @"name", @"california", @"state", nil];
    
    NSArray *people = [NSArray arrayWithObjects:arnold, jimmy, henry, woz, nil];
    
    NSLog(@"Unique States:\n %@", [people valueForKeyPath:@"@distinctUnionOfObjects.state"]);
    
    // OUTPUT
    // Unique States:
    // "california",
    // "michigan",
    // "new york"
    

提交回复
热议问题