Re: NSDictionary design bug (was: Re: Ugly bug in Foundation, beware!)
Re: NSDictionary design bug (was: Re: Ugly bug in Foundation, beware!)
- Subject: Re: NSDictionary design bug (was: Re: Ugly bug in Foundation, beware!)
- From: Patrick Machielse <email@hidden>
- Date: Sun, 06 Jun 2004 23:07:45 +0200
op 06-06-2004 17:00 schreef Marcel Weiher
>
> As the copy will satisfy the -hash and -isEqual "identity", the copy
>
> is just as good as the original for the purpose.
>
>
If there is one "invariant" a dictionary should obey, it is that the
>
following must hold:
>
>
[dict setObject:b forKey:a];
>
b == [dict objectForKey:a];
>
>
NSDictionary does not obey this invariant. I have created a little
>
test program to make this more clear. We create an NSObject subclass
>
that faithfully implements the NSCopying protocol as documented. We
>
can use objects of this class as keys to our dictionary, but we can
>
never get the objects back out again, even using the exact same key!!
>
>
It also faithfully implements the recommendation for "hash", and yet it
>
breaks...
>
>
------------------------ dictbug.m ------------
>
#import <Foundation/Foundation.h>
>
>
@interface MyObject : NSObject <NSCopying>
>
{}
>
@end
>
@implementation MyObject
>
-copyWithZone:(NSZone*)zone
>
{
>
id copy=[[[self class] alloc] init];
>
return copy;
>
}
>
@end
When you copy the key here, you create a new object. *BUT* NSObject, and
therefore MyObject implements isEqual: as '==' so the copied key is not
equal anymore to the one you passed to the dictionary... Hence, you can
never retreive your object from the dictionary.
You should either make a clever isEqual: implementation for MyObject, or
heed the recomendation from the documentation:
Implement NSCopying by retaining the original instead of creating a new
copy when the class and its contents are immutable.
Which seems suitable for keys.
Before people become paranoid and start seeing bugs _everywhere_ I vote in
favour of having a tea break :-)
Patrick
---
Hieper Software
w: www.hieper.nl
e: email@hidden
_______________________________________________
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.