Objective-C:使用自定义对象键从 NSMutableDictionary 获取值
我一直使用 NSDictionaries 以字符串作为键,以及网络/书籍/等上的几乎所有示例。是一样的。我想我应该尝试使用自定义对象作为密钥。我已经阅读了有关实现“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
现在我尝试仅添加带有简单字符串值的这些对象之一,然后将字符串值返回以登录到控制台:
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"
不幸的是日志显示(空)。我很确定我错过了一些非常明显的东西,并且感觉我需要另一双眼睛。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSDictionary
key 对象使用三种方法:-(NSUInteger)hash
-(BOOL)isEqual:(id)other
-(id )copyWithZone:(NSZone*)zone
hash
和isEqual:
的默认NSObject
实现仅使用对象的指针,因此当你的对象通过copyWithZone
复制:副本和原始对象不再相等。您需要的是这样的:
从文档中找到这一点有点困难。 NSDictionary 概述 告诉您有关
isEqual:
和NS复制
:如果您查看
-[NSObject isEqual:]
的文档它告诉关于哈希
:NSDictionary
key objects work off three methods:-(NSUInteger)hash
-(BOOL)isEqual:(id)other
-(id)copyWithZone:(NSZone*)zone
The default
NSObject
implementation ofhash
andisEqual:
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
:我认为你的类需要定义:
这就是字典可能使用的来确定你的键是否等于字典中已使用的键。
I think your class needs to define:
That is what is probably used by the dictionary to determine if your key is equal to one already used in the dictionary.