我有这个代码
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个标签。有什么更短的方法/代码来做吗?
答案 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中的键匹配,则可以使这更简单(那么您可以使用名称数组而不是字典)。