tags:

views:

69

answers:

2

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 called 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!

+3  A: 

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;
}
e.James
A: 

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)?

twinkle
You should post this comment as a comment on e.James answer. In any case, your code doesn't swap players; it'll always make p2 the current player and p1 the current opponent.
bbum
@twinkle: I'm not sure about combining the `@property` declarations onto one line. I've never done it that way, but it might work.
e.James
Combined declarations work fine though you obviously can't have both assign and retain on the same line. :)
bbum