I’ve always used NSDictionaries with strings as keys, and pretty much all the examples on the web/books/etc. are the same. I figured that I’d try it with a custom object for a key. I’ve read up on implementing the “copyWithZone” method and created the following basic class:
@interface CustomClass : NSObject
{
NSString *constString;
}
@property (nonatomic, strong, readonly) NSString *constString;
- (id)copyWithZone:(NSZone *)zone;
@end
@implementation CustomClass
@synthesize constString;
- (id)init
{
self = [super init];
if (self) {
constString = @"THIS IS A STRING";
}
return self;
}
- (id)copyWithZone:(NSZone *)zone
{
CustomClass *copy = [[[self class] allocWithZone: zone] init];
return copy;
}
@end
Now I’m trying to just add one of these objects with a simple string value, and then getting the string value back out to log to the console:
CustomClass *newObject = [[CustomClass alloc] init];
NSString *valueString = @"Test string";
NSMutableDictionary *dict =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:valueString, newObject, nil];
NSLog(@"Value in Dictionary: %@", [dict objectForKey: newObject]);
// Should output "Value in Dictionary: Test string"
Unfortunately the log displays a (null). I’m pretty sure I’m missing something really obvious, and feel like I need another set of eyes.
NSDictionarykey objects work off three methods:-(NSUInteger)hash-(BOOL)isEqual:(id)other-(id)copyWithZone:(NSZone*)zoneThe default
NSObjectimplementation ofhashandisEqual:only use the object’s pointer, so when your object is copied viacopyWithZone:the copy and the original object are no longer equal.What you need is something like this:
It’s a little bit difficult to find this out from the documentation. The overview for NSDictionary tells you about
isEqual:andNSCopying:And if you have a look at the documentation for
-[NSObject isEqual:]it tells you abouthash: