开发者

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 hav开发者_如何学Ce 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.


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.


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
}


Looking through the documentation, it seems that there is no way to really handle this special case of yours. You're going to have to write some custom code to handle this. Personally, I would recommend using -sortedArrayUsingDescriptors: and then comparing the arrays, but that's just me. You could also go enumerate through one set, then narrow down the other using -filteredSetUsingPredicate: and get its count.

Whichever method you use, consider the fact that its probably not going to be super efficient. This might be unavoidable, but there are probably ways to go about it that are better than others. Food for thought.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜