Re-assignment of variable doesn't work
I have a puzzling problem -- it seems like it should be so easy to do but somehow it is not working. I have an object c开发者_JAVA技巧alled Player. The Manager class has four instances of Player:
@interface Manager
{
Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent;
}
// @property...
The Manager object has initPlayers and swapPlayers methods.
-(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
}
What am I missing? Thanks in advance!
Without knowing how your accessors are set up, it will be difficult to troubleshoot the code as-is. That being said, here is how your accessors and code should be set up:
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;
}
It turns out the problem was somewhere unrelated in the code and I misread the symptoms of the problem! But just for the sake of discussion, why is it necessary to have @property on multiple lines, and to use a temp variable to swap the players (as per e.James answer)?
精彩评论