选择所有玩家对象目标C.

时间:2012-10-30 15:28:49

标签: objective-c object selector

我刚刚开始使用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;
}

1 个答案:

答案 0 :(得分: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;
}