我有一个令人费解的问题 - 似乎应该这么容易做但不知何故它不起作用。我有一个名为Player的对象。 Manager类有四个Player实例:
@interface Manager
{
Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent;
}
// @property...
Manager对象具有initPlayers和swapPlayers方法。
-(void) initPlayers { // this works fine
self.p1 = [[Player alloc] init];
self.p2 = [[Player alloc] init];
self.mCurrentPlayer = self.p1;
self.mCurrentOpponent = self.p2;
}
-(void) swapPlayers { // this swapping of pointer doesn't work
self.mCurrentPlayer = self.p2;
self.mCurrentOpponent = self.p1;
// When I look at the pointer in debugger, self.mCurrentPlayer is still self.p1. :-(
// I even tried first setting them to nil,
// or first releasing them (with an extra retain on assignment) to no avail
}
我错过了什么?提前谢谢!
答案 0 :(得分:3)
如果不知道如何设置访问者,就很难对代码进行故障排除。话虽如此,这里是你的访问者和代码应该的设置方式:
<强> Manager.h 强>
@interface Manager
{
Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent;
}
@property (nonatomic, retain) Player *p1;
@property (nonatomic, retain) Player *p2;
@property (nonatomic, assign) Player *mCurrentPlayer;
@property (nonatomic, assign) Player *mCurrentOpponent;
@end
<强> Manager.m 强>
-(void) initPlayers {
self.p1 = [[[Player alloc] init] autorelease];
self.p2 = [[[Player alloc] init] autorelease];
self.mCurrentPlayer = self.p1;
self.mCurrentOpponent = self.p2;
}
-(void) swapPlayers {
Player * temp = self.mCurrentPlayer;
self.mCurrentPlayer = self.mCurrentOpponent;
self.mCurrentOpponent = temp;
}
答案 1 :(得分:0)
事实证明问题在代码中无处不在,我误解了问题的症状!但仅仅为了讨论,为什么有必要在多行上使用@property,并使用temp变量来交换玩家(根据e.James的回答)?