I have some problems with NSMutableSet in Objective-C. I found out that NSSet will compare the hash code of two objects to decide if they are identical or not. The problem is that I implemented a class that is a subclass of NSObjectitself. This class has a property NSString *name. What I want to do is when the instances of this user class have the same value for the name variable, they must be identical, and such an identical class should not be duplicated when added to the NSMutableSet.
So I redefine the function - (NSUInteger)hash, and debugging shows that it returns the same hash for my two instances obj1, obj2 (obj1.name == obj2.name). But when I added obj1, obj2 in NSMutableSet, NSMutableSetstill contained both obj1, obj2 in it.
I tried two NSStringthat have the same value, and then added them to NSMutableSet, the set will be only one NSString.
What could be the solution? Thanks for any help!
Custom Class: Object.h:
#import <Foundation/Foundation.h>
@interface Object : NSObject
@property (retain) NSString *name;
@end
Object.m
@implementation Object
@synthesize name;
-(BOOL)isEqualTo:(id)obj {
return [self.name isEqualToString:[(Object *)obj name]] ? true : false;
}
- (NSUInteger)hash {
return [[self name] hash];
}
@end
and main:
#import <Foundation/Foundation.h>
#import "Object.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Object *obj1 = [[Object alloc]init];
Object *obj2 = [[Object alloc]init];
obj1.name = @"test";
obj2.name = @"test";
NSMutableSet *set = [[NSMutableSet alloc] initWithObjects:obj1, obj2, nil];
NSLog(@"%d", [obj1 isEqualTo:obj2]);
NSLog(@"%ld", [set count]);
}
return 0;
}
source
share