hash and isEqual not working as expected
hash and isEqual not working as expected
- Subject: hash and isEqual not working as expected
- From: Eyal Redler <email@hidden>
- Date: Sat, 10 Jan 2004 18:06:19 +0200
Hi All,
Until now I thought that if I don't define hash for my classes things
will not work well. I found a few classes where I forgot to define hash
and discovered that there is no difference:
Even though the class breaks the rule saying "If two objects are equal
(as determined by the isEqual: method), they must return the same hash
value" the behavior inside Arrays dictionaries and attributed string
seem to be OK.
In the following example you'll notice that hash is not defined for
MyClass but the dictionary equality test doesn't fail and the string
attribute is correctly spread out across the whole string. The hash
results are different but they don't seem to be called from the
comparison code.
Is there an explanation for this?
TIA!
@interface MyClass : NSObject
{
NSString* string;
}
- (id) initWithString:(NSString*)aString;
@end
@implementation MyClass
- (id) initWithString:(NSString*)aString
{
self = [super init];
if (self) {
string=[aString retain];
}
return self;
}
- (void)dealloc
{
[string release];
[super dealloc];
}
- (BOOL)isEqualToMyClass:(MyClass*)otherObject
{
if (![string isEqualToString:otherObject->string])
return NO;
return YES;
}
- (BOOL)isEqual:(id)otherObject
{
if (self!=otherObject)
{
if ([otherObject class]==[self class])
return [self isEqualToMyClass:otherObject];
else
return NO;
}
return YES;
}
// hash is not defined for MyClass
@end
MyClass* objectA;
MyClass* objectB;
NSDictionary* dictionaryA;
NSDictionary* dictionaryB;
NSMutableAttributedString* aString;
objectA =[[MyClass alloc] iniwWithString:@"Hello world!"];
objectB =[[MyClass alloc] initWithFamily:@"Hello world!"];
dictionaryA=[NSDictionary dictionaryWithObject: objectA
forKey:@"myKey"];
dictionaryB=[NSDictionary dictionaryWithObject: objectB
forKey:@"myKey"];
aString=[[NSMutableAttributedString alloc] init];
[[aString mutableString] appendString:@"ABCDEFGH"];
[aString addAttribute:@"anAttribute" value: objectA
range:NSMakeRange(0,4)];
[aString addAttribute:@"anAttribute" value: objectB
range:NSMakeRange(4,4)];
if ([dictionaryA isEqual:dictionaryB])
NSLog(@"Dicts EQUAL");
else
NSLog(@"Dicts NOT EQUAL");
NSLog(@"String description: %@",[aString description]);
NSLog(@"Object A hash: %d",[objectA hash]);
NSLog(@"Object B hash: %d",[objectB hash]);
[aString release];
[objectA release];
[objectB release];
Eyal Redler
------------------------------------------------------------------------
------------------------
"If Uri Geller bends spoons with divine powers, then he's doing it the
hard way."
--James Randi
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.