我想用我自己的对象作为键将东西保存到 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];
此时,origin已经再次为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;
}
在我看来,有时它无法保存给定键的对象......?我该怎么做才能解决它,请帮忙