Iphone 字符串标识要更新的iVar
我有一系列的5个IVAR。(highscore01、highscore02、highScore03、highScore04、highScore05)我想用整数值更新特定的iVar。IVAR被定义为INT。IVAR在一个叫做HighScores的班级里 要更新的特定iVar是其中存储的当前值最低的iVar。我想用新值替换最低值 我有一个方法,它用最小的值标识ivar,并返回一个字符串“theString”,其中包含要更新的ivar的名称 我的问题是:如何使用“字符串”更新正确的iVar 下面是一个代码示例Iphone 字符串标识要更新的iVar,iphone,objective-c,Iphone,Objective C,我有一系列的5个IVAR。(highscore01、highscore02、highScore03、highScore04、highScore05)我想用整数值更新特定的iVar。IVAR被定义为INT。IVAR在一个叫做HighScores的班级里 要更新的特定iVar是其中存储的当前值最低的iVar。我想用新值替换最低值 我有一个方法,它用最小的值标识ivar,并返回一个字符串“theString”,其中包含要更新的ivar的名称 我的问题是:如何使用“字符串”更新正确的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
}
最后一行是我尝试将“字符串”中标识的iVar设置为新分数。“字符串”确实包含要更新的iVar的名称,即“HighScore03”等
如果我是手动设置的,它将是;
HighScores.HighScores03=主要得分.ScoresTotal
如果我是你的话,我会使用可变数组来进行排序并轻松挑选出最低的项目
///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];
}
我认为mjdth的解决方案可能是最好的,但是您也可以使用-setValue:forKey:,尽管您必须切换到使用NSNumbers,而不是ints
[theHighScores setValue: [NSNumber numberWithInt: mainScores.scoreTotal] forKey: [theHighScores findLowestHighScore]];
听起来你在做一些基本的练习。具体来说,使用
谢谢你的帮助。设置可变数组肯定是更好的方法。
int newValue = 1;
SEL methodName = NSSelectorFromString(@"setHighScore03:");
[theHighScores performSelector:methodName withObject:newValue];