我有一系列5个iVars。 (highscore01,highscore02,highScore03,highScore04,highScore05)我想用整数值更新特定的iVar。 iVars定义为整数。 iVars属于一个名为HighScores的类。
要更新的特定iVar是存储在其中的当前值最低的iVar。我想用新值替换最低值。
我有一个方法可以识别具有最低值的ivar,并返回一个字符串“theString”,其中包含要更新的iVar的名称。
我的问题:如何使用“theString”更新正确的iVar。
以下是代码示例。
// If any of the highScore iVars contain 0, then they are still empty.
// Find the first empty iVar and store score there.
if (scoreVarsFullFlag == NO) // Flag to indicate if any iVars are still zero
{
if (theHighScores.highScore01 == 0)
theHighScores.highScore01 = mainScores.scoreTotal;
else if (theHighScores.highScore02 == 0)
theHighScores.highScore02 = mainScores.scoreTotal;
else if (theHighScores.highScore03 == 0)
theHighScores.highScore03 = mainScores.scoreTotal;
else if (theHighScores.highScore04 == 0)
theHighScores.highScore04 = mainScores.scoreTotal;
else if (theHighScores.highScore05 == 0)
{
theHighScores.highScore05 = mainScores.scoreTotal;
scoreVarsFullFlag = YES; // Last scores iVar turns nonzero - set Flag to YES, to indicate no non-zero iVars
}
}
else
{
NSLog(@"The Lowest is at %@", [theHighScores findLowestHighScore]);
NSString * theString;
theString = [NSString stringWithString:[theHighScores findLowestHighScore]];
NSLog(@"The String is: %@", theString);
theHighScores.theString = mainScores.scoreTotal; // This fails
}
最后一行是我尝试将“theString”中标识的iVar设置为新的分数。 “theString”确实包含要更新的iVar的名称,即“HighScore03”等。
如果我手动设置,那将是; theHighScores.highScore03 = mainScores.scoreTotal;
非常感谢任何见解。
答案 0 :(得分:1)
如果我是你,我只是使用一个可变数组来允许排序并轻松挑选最低项目。
///store this in your app delegate
NSMutableArray *highscores = [[NSMutableArray alloc] init];
//then when you want to add a high score
[highscores addObject:[NSNumber numberWithDouble:mainScores.scoreTotal]];
NSSortDescriptor *myDescriptor;
myDescriptor = [[NSSortDescriptor alloc] initWithKey:@"doubleValue" ascending:NO];
[highscores sortUsingDescriptors:[NSArray arrayWithObject:myDescriptor]];
///remove the last object if it's over 5
if ([highscores count]>5) {
[highscores removeLastObject];
}
答案 1 :(得分:1)
我认为mjdth的解决方案可能是最好的,但你也可以使用-setValue:forKey :,尽管你必须切换到使用NSNumbers而不是int。
[theHighScores setValue: [NSNumber numberWithInt: mainScores.scoreTotal] forKey: [theHighScores findLowestHighScore]];
答案 2 :(得分:0)
听起来你正试图做一些基本的type introspection。具体来说,使用NSSelectorFromString。
int newValue = 1;
SEL methodName = NSSelectorFromString(@"setHighScore03:");
[theHighScores performSelector:methodName withObject:newValue];