1

我刚开始使用Objective C,我想知道选择所有其他玩家将isActive属性设置为NO的正确语法是什么。谢谢!

- (void) playerBuzzedIn: (XGPlayer *) activePlayer
{
    if (activePlayer) {
        activePlayer.isActive = YES;
    }
    else
       //set all other isActive = NO
    self.currentGameState = results;
}

我在想这样的事情,对吗:

for (XGPlayer *player in self.players) {
player.isActive = NO;
}
4

1 回答 1

0

首先你需要一份所有玩家的名单;让我们假设它是这样的:

NSMutableArray *_allplayers = ...;

然后在您的方法中,您可以将所有玩家设置为非活动状态,除了刚刚加入的玩家:

- (void) playerBuzzedIn: (XGPlayer *) activePlayer
{
    if (activePlayer)
    {
        for (XGPlayer *player in _allPlayers)
        {
            player.isActive = activePlayer == player;   // Or perhaps [activePlayer isEqual:player] ?
        }
    }
    self.currentGameState = results;
}

另一种方法是保留一个指向当前活跃玩家的指针:

在 .h 文件中:

@interface Whatever : NSObject
{
    XGPlayer *_activePlayer = nil;
}

@property (retain, nonatomic, readonly) XGPlayer *activePlayer;

@end

在 .m 文件中:

// Private Methods
@interface Whatever ()
- (void)setActivePlayer:(XGPlayer *)activePlayer
@end

@implementation Whatever

@synthesize activePlayer = _activePlayer;

// Private setter method
- (void)setActivePlayer:(XGPlayer *)activePlayer
{
    [activePlayer retain];     // If not using ARC
    [_activePlayer release];   // If not using ARC
    _activePlayer = activePlayer;
}

- (void) playerBuzzedIn: (XGPlayer *) activePlayer
{
    self.activePlayer.isActive = NO;
    activePlayer.isActive = YES;
    self.activePlayer = activePlayer;
    self.currentGameState = results;
}
于 2012-10-30T15:46:50.683 回答