tags:

views:

34

answers:

1

I have seen some questions/answers regarding filter objects by using NSSet/NSMutableSet. Those cases use simple type of objects such as NSString or int. The following is an example of codes used to filter NSString objects:

NSSet smallArray = [[NSSet alloc] initWithObjects:@"0", @"1", @"2", nil];
NSArray bigArray = [[NSArray alloc] initWithObjects:@"0", @"1", @"4", @"5", ..., nil];
NSMutableSet *intersection = [NSMutableSet setWithArray:smallArray];
[intersection intersectSet:[NSSet setWithArray:bigArray];
NSArray *result = [NSArray arrayWithSet:intersection];

I am not sure how it works if objects in set or array are Object-C class instances. Take the following class as example:

@interface MyObject: NSObject {
   int id;
   NSString *name;
   NSString *city;
   ...
}

I am not sure how set's intersetSet: works with above type objects. If I want to get intersect set of smallArray of MyObject objects and bigArray by only comparing id, I doubt if I can use intersetSet: selector method? If not, not sure if I should add any method to MyObject class so that set knows how to compare objects?

+1  A: 

You need to implement isEqual: (and also hash) on MyObject so that if two objects "match", then it returns YES. Then the set intersection code should work automatically.

Here's a quick and dirty sample from the documentation. Also check out this SO question.

Robot K
Your answer makes sense. I'll try it first Thanks!
David.Chu.ca