Reassigning a variable does not work

I have a mysterious problem - it seems like it should be so easy to do, but somehow it doesn't work. I have an object called Player. The Manager class has four Player instances:

@interface Manager
{
    Player *p1, *p2, *mCurrentPlayer, *mCurrentOpponent;  
}
// @property...

The Manager object has the 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
source share
2 answers

Not knowing how your accessors will be configured, it will be difficult to troubleshoot the code as is. In this case, you need to configure your accessors and code:

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;
}
+3
source

, - , ! , @property ( e.James)?

0

Source: https://habr.com/ru/post/1731598/


All Articles