Objective-C:使用自定义对象键从NSMutableDictionary获取值

5St*_*yan 4 dictionary object objective-c nsmutabledictionary

我总是使用带有字符串的NSDictionaries作为键,几乎所有的例子都在web/books/etc上.是相同的.我想我会用一个自定义对象来尝试它.我已经阅读了实现"copyWithZone"方法并创建了以下基本类:

@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
Run Code Online (Sandbox Code Playgroud)

现在我试图用一个简单的字符串值添加其中一个对象,然后返回字符串值以登录到控制台:

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"
Run Code Online (Sandbox Code Playgroud)

不幸的是,日志显示(null).我很确定我错过了一些非常明显的东西,觉得我需要另一双眼睛.

Tom*_*ing 7

NSDictionary 关键对象有三种方法:

  • -(NSUInteger)hash
  • -(BOOL)isEqual:(id)other
  • -(id)copyWithZone:(NSZone*)zone

默认NSObject实现hash并且isEqual:仅使用对象的指针,因此当您的对象通过copyWithZone:副本复制并且原始对象不再相等时.

你需要的是这样的:

@implementation CustomClass

-(NSUInteger) hash;
{
    return [constString hash];
}

-(BOOL) isEqual:(id)other;
{
    if([other isKindOfClass:[CustomClass class]])
        return [constString isEqualToString:((CustomClass*)other)->constString];
    else
        return NO;
}
- (id)copyWithZone:(NSZone *)zone
{
    CustomClass *copy = [[[self class] allocWithZone: zone] init];
    copy->constString = constString; //might want to copy or retain here, just incase the string isn't a constant
    return copy;
}

@end
Run Code Online (Sandbox Code Playgroud)

从文档中找到它有点困难.该对的NSDictionary概述告诉你isEqual:NSCopying:

在字典中,键是唯一的.也就是说,单个字典中没有两个键是相等的(由isEqual :)确定.通常,密钥可以是任何对象(前提是它符合NSCopying协议 - 见下文),但请注意,当使用键值编码时,密钥必须是字符串(请参阅"键值编码基础").

如果您查看文档,-[NSObject isEqual:]它会告诉您hash:

如果两个对象相等,则它们必须具有相同的哈希值.如果在子类中定义isEqual:并打算将该子类的实例放入集合中,则最后一点尤为重要.确保您还在子类中定义哈希.