Re: Objects as keys NSMutableDictionary
Re: Objects as keys NSMutableDictionary
- Subject: Re: Objects as keys NSMutableDictionary
- From: "Adam R. Maxwell" <email@hidden>
- Date: Mon, 10 Jul 2006 06:33:01 -0700
On Jul 9, 2006, at 22:16, Rosyna wrote:
No biggy...
NSMutableDictionary* happyDict=[(NSMutableDictionary*)
CFDictionaryCrateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks) autorelease];
Now you can treat happyDict like any other NSMutableDicitonary and
put anything as the keys. Toll free bridging at work.
When I suggested a CFDictionary in my reply, I added a caveat that
values should be added with CF functions. Here's why:
#import <Foundation/Foundation.h>
@interface TestObject : NSObject <NSCopying> @end
@implementation TestObject
- (id)copyWithZone:(NSZone *)aZone
{
[NSException raise:NSInternalInconsistencyException
format:@"Must not copy objects of class %@", [self class]];
return nil; // make the compiler happy...
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableDictionary* cfDict = [(NSMutableDictionary*)
CFDictionaryCreateMutable(CFAllocatorGetDefault(), 0,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)
autorelease];
TestObject *obj = [[TestObject alloc] init];
CFDictionaryAddValue((CFMutableDictionaryRef)cfDict, obj, CFSTR
("a CFStringRef"));
[cfDict setObject:@"Value" forKey:obj];
[pool release];
return 0;
}
Using the CFDictionaryAddValue function, things work. Using
setObject:forKey:, an exception is raised when the key is copied.
#0 0x9295f120 in _NSRaiseError
#1 0x9295ee5c in +[NSException raise:format:]
#2 0x00027c7c in -[TestObject copyWithZone:] at keyTest.m:9
#3 0x92925490 in -[NSCFDictionary setObject:forKey:]
the default implementation of -hash just returns the pointer value,
IIRC, so it's fine to use mutable objects as keys since their
pointer value does not change in relation to their content.
Yes. In that case, though, isEqual: must also be based on pointer
equality (which is also the default).
Adam
Ack, at 7/10/06, email@hidden said:
"Methods that add entries to dictionaries-whether as part of
initialization (for all dictionaries) or during modification (for
mutable dictionaries)- don't add each value object to the
dictionary directly, but copy each key argument and add the copy
to the dictionary. In Objective-C, the dictionary copies each key
argument (keys must conform to the NSCopying protocol) and adds
the copies to the dictionary. Each corresponding value object
receives a retain message to ensure that it won't be deallocated
before the dictionary is through with it."
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden