gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 04:01:23 27 4
gpt4 key购买 nike

我一直使用以字符串作为键的 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"

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

最佳答案

NSDictionary 关键对象使用三种方法:

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

hashisEqual: 的默认 NSObject 实现只使用对象的指针,所以当你的对象通过 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

从文档中找出这一点有点困难。 overview for NSDictionary告诉你 isEqual:NSCopying:

Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see “Key-Value Coding Fundamentals”).

如果你看一下 documentation for -[NSObject isEqual:]它告诉你关于 hash 的信息:

If two objects are equal, they must have the same hash value. This last point is particularly important if you define isEqual: in a subclass and intend to put instances of that subclass into a collection. Make sure you also define hash in your subclass.

关于Objective-C:使用自定义对象键从 NSMutableDictionary 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480636/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com