在Java中把一个自定义的类生成的对象作为HashTable的key是天生可行的,但是在Objective C中,NSDictionary的key使用的是copy方法,所以自定义的类必须要实现copyWithZone才可以。
假设现在有一个CustomClass:
@interface CustomClass : NSObject <NSCopying>
@property (strong) NSString *name;
@end
这个时候,如果不写copyWithZone,那么把它当作NSDictionary key时,就会报错。于是,需要实现copyWithZone方法:
- (id)copyWithZone:(NSZone *)zone
{
id aCopy = [[[self class] alloc]init];
if (aCopy) {
[aCopy setName:[self.name copyWithZone:zone]];
}
return aCopy;
}
这样做之后,就可以当作key传到NSDictionary中去了。