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: Mon, 07 Jun 2004 23:46:30 +0200
op 07-06-2004 14:57 schreef Marco Scheurer
>
On Jun 7, 2004, at 1:04 PM, Patrick Machielse wrote:
>
>
> You can consider isEqual: whatever you like, as long as you obey the implied
>
> rule:
>
>
>
> when b = [a copy] then [b isEqual:a] == YES must hold
>
>
Must hold for how long? If 'a' is a mutable string then 'b' will be
>
immutable and a snapshot of 'a' at the time of the copy. If 'a' later
>
changes, [b isEqual:a] will not hold, obviously.
Sure, and that is not a problem. The only requirement is that directly after
taking the snapshot using 'copy' the objects are considered equal.
>
> When you willingly violate this rule, as you do in your example, you really
>
> lose all hope of NSDictionary functioning.
>
>
Yes but the copying of the keys brings no advantage to the user, and
>
only adds burden:
>
>
(1) if the key is immutable then copying is useless (and often defaults
>
to retain anyway)
So this isn't a problem.
>
(2) if the key is mutable then
>
(2a) if its value does not change between storage and retrieval then
>
copying is useless
Granted. But to just use retain you must know in advance that it won't
change, which may not be easy. And if the key then _does_ change by accident
it will result in a hard to find bug.
>
(2b) if its value change between storage and retrieval then you will
>
not find your object anyway.
This is only true if you use the same instance of the key to retrieve the
stored object! You can create a new key that 'isEqual' to the original one
and retrieve the stored object. On the other hand, if the dictionary only
stores a reference to the key you are indeed in trouble...
Copying the keys allows you to change the key and still be able to find the
object.
So code like this will work:
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[] )
{
id pool=[NSAutoreleasePool new];
NSMutableString *key = [NSMutableString stringWithString:@"1"];
id dict=[NSMutableDictionary dictionary];
[dict setObject:@"first" forKey:key];
[key appendString:@"2"];
[dict setObject:@"second" forKey:key];
NSLog(@"first was: %@", [dict objectForKey:@"1"]);
[pool release];
return 0;
}
In my view this makes NSDictionary more robust, but it may not be
everybody's cup of tea. Still, I believe this to be a conscious design
decision, and not a bug. But only the people who made it this way really
know for sure ;-)
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.