是否有更简单的方法来制作这样的东西?

时间:2012-02-11 00:16:56

标签: iphone objective-c ios xcode ipad

像Q

一样

我有这个代码

K1player1D.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"K1scoredLabel1"];
K1player1L.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"K1scorelLabel1"];
K1player1K.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"K1scorekLabel1"];
K1player1Q.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"K1scoreqLabel1"];
K1player1T.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"K1scoretLabel1"];
在viewDidLoad中,对于四个玩家,所以它的16个标签。有什么更短的方法/代码来做吗?

3 个答案:

答案 0 :(得分:0)

您可以使用NSMutableArray填充其中的所有UILabel并循环播放:

int i=1;
for(Player in ArrayOfUILabel){
    Player.text = [[NSUserDefaults standardUserDefaults] objectForKey:(@"K1scoredLabel%d",i)];
    i++;
}

答案 1 :(得分:0)

修改

我会将它们放在NSDictionary

NSDictionary * playerDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                     K1player1D,@"K1scoredLabel1",
                                     K1player1L,@"K1scorelLabel1",
                                     K1player1K,@"K1scorekLabel1",
                                     K1player1Q,@"K1scoreqLabel1",
                                     K1player1T,@"K1scoretLabel1",nil];

for(NSString * key in [playerDict allKeys]){
    PlayerObject * player = [playerDict objectForKey:key];
    player.text = [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

答案 2 :(得分:0)

使用Joels的答案结合KVC(键值编码),还有另一种方法可以做到这一点。我不知道这是否是一种特别好的方法,但为了完整起见,我将其包括在内:

NSDictionary * playerDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                 @"K1player1D",@"K1scoredLabel1",
                                 @"K1player1L",@"K1scorelLabel1",
                                 @"K1player1K",@"K1scorekLabel1",
                                 @"K1player1Q",@"K1scoreqLabel1",
                                 @"K1player1T",@"K1scoretLabel1",nil];

for(NSString * key in [playerDict allKeys]){
    NSString *labelName = [playerDict objectForKey:key];
    UILabel *label = [self valueForKey:labelName]; // grab the correct label using KVC
    label.text = [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

如果标签名称与NSUserDefaults中的键匹配,则可以使这更简单(那么您可以使用名称数组而不是字典)。