Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing NSSets by a single property

I'm trying to determine if two NSSets are "equal" but not in the sense of isEqualToSet. Items in the two sets are the same class but are not the same object, or even references to the same object. They will have one property that is the same though - let's call it 'name'.

Is my best bet in comparing these two sets to do a simple set count test, then a more complex objectsPassingTest: on each item in one set, making sure an item with the same name is in the other set? I'm hoping that something simpler exists to handle this case.

like image 778
Nick Avatar asked Feb 15 '26 03:02

Nick


2 Answers

I had the same problem, but I needed to compare multiple properties at the same time (class User with properties Name and Id).

I resolved this by adding a method returning an NSDictionary with the properties needed to the class:

- (NSDictionary *)itemProperties
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:self.name forKey:@"name"];
    [dict setObject:self.id forKey:@"id"];
    return dict;
}

and then using valueForKey: as Kevin Ballard mentioned:

BOOL userSetsEqual = [[userSet1 valueForKey:@"itemProperties"]
    isEqualToSet:[userSet2 valueForKey:@"itemProperties"]];

... where userSet1 and userSet2 were the NSSets that contained User objects.

like image 170
Markus Rautopuro Avatar answered Feb 17 '26 21:02

Markus Rautopuro


You could just call valueForKey: on both sets and compare the results.

if ([[set1 valueForKey:@"name"] isEqualToSet:[set2 valueForKey:@"name"]]) {
    // the sets match your criteria
}
like image 36
Lily Ballard Avatar answered Feb 17 '26 19:02

Lily Ballard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!