我希望将自己的对象作为键
保存到NSMutableDictionary中为此我实现了我的对象的NSCopying协议,以及它使用的所有元素 昨晚,它确实保存了这些物品,今天早上,当我运行完全相同的代码时,它不再保存它了。
为什么会这样?
这些是我的NSCopying方法:
- (id)copyWithZone:(NSZone *)zone{
Player *player = [[[self class]allocWithZone:zone]init];
if(player){
player->name = [name copyWithZone:zone];
player->deck = [deck copyWithZone:zone];
}
return player;
}
-(id)copy{
Player *player = [[[self class]alloc]init];
if(player){
player->name = [name copy];
player->deck = [deck copy];
}
return player;
}
-(BOOL)isEqual:(id)object{
if(![object isKindOfClass:[Player class]]){
return NO;
}
Player *player = (Player *)object;
return [self.name isEqualToString:[player name]];
}
-(id)copyWithZone:(NSZone *)zone{
DeckOfCards *deckOfCards = [[[self class]allocWithZone:zone]init];
if(deckOfCards){
deckOfCards->deck = [deck copyWithZone:zone];
}
return deckOfCards;
}
-(id)copy{
DeckOfCards *deckOfCards = [[[self class]alloc]init];
if(deckOfCards){
deckOfCards->deck = [deck copy];
}
return deckOfCards;
}
这就是我想要使用的对象: 在viewDidLoad
中CGPoint player1CardOrigin = CGPointMake(20, 160);
CGPoint player2CardOrigin = CGPointMake(180, 160);
[origins setObject:[NSValue valueWithCGPoint:player1CardOrigin] forKey:player1];
[origins setObject:[NSValue valueWithCGPoint:player2CardOrigin] forKey:player2];
稍后在代码
中的某个地方Player *player = [game playerToMove];
CGPoint origin = [[origins objectForKey:player]CGPointValue];
此时,原点已经是0,0而不是正确的值
我不明白的是,为什么昨天它有效,今天它没有? 我做错了什么?
进一步检查显示:
- (IBAction)click:(id)sender {
Player *player1 = [Player playerWithName:[self getNameFromTextField:tfPlayer1]];
Player *player2 = [Player playerWithName:[NSString stringWithFormat:@"%@ ",[self getNameFromTextField:tfPlayer2]]];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:@"player1" forKey:player1];
[dict setObject:@"player2" forKey:player2];
NSLog(@"dict: %@",dict);
}
多次单击所述按钮,产生以下输出:
2013-06-29 10:06:10.165 CardWarGame[3109:c07] dict: {
"2 \n(0)" = (null);
"1\n(0)" = player1;
}
2013-06-29 10:06:13.612 CardWarGame[3109:c07] dict: {
"1\n(0)" = player1;
"2 \n(0)" = player2;
}
2013-06-29 10:06:19.407 CardWarGame[3109:c07] dict: {
"1\n(0)" = player1;
"2 \n(0)" = player2;
}
2013-06-29 10:06:20.798 CardWarGame[3109:c07] dict: {
"1\n(0)" = player1;
"2 \n(0)" = (null);
}
2013-06-29 10:06:21.780 CardWarGame[3109:c07] dict: {
"2 \n(0)" = (null);
"1\n(0)" = player1;
}
2013-06-29 10:06:22.620 CardWarGame[3109:c07] dict: {
"2 \n(0)" = player2;
"1\n(0)" = player1;
}
2013-06-29 10:06:23.402 CardWarGame[3109:c07] dict: {
"2 \n(0)" = (null);
"1\n(0)" = player1;
}
在我看来,有时它无法保存给定密钥的对象......? 我该怎么做才能解决它,请帮忙
答案 0 :(得分:0)
我也应该覆盖这种方法:
-(NSUInteger)hash{
NSLog(@"player hash");
return [[self name]hash];
}
然后每次都有效