Строка идентифицирует iVar для обновления - PullRequest
0 голосов
/ 18 декабря 2009

У меня есть серия из 5 iVars. (highscore01, highscore02, highScore03, highScore04, highScore05) Я хочу обновить конкретный iVar с целочисленным значением. IVars определяются как целые. IVars относятся к классу HighScores.

Конкретный обновляемый 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
}

В последней строке я пытаюсь установить iVar, указанный в "theString", на новый номер счета. «theString» содержит имя обновляемого iVar, то есть «HighScore03» и т. д.

Если бы я настраивал это вручную, это было бы; theHighScores.highScore03 = mainScores.scoreTotal;

Любое понимание будет высоко ценится.

Ответы [ 3 ]

1 голос
/ 18 декабря 2009

Я думаю, что решение mjdth, вероятно, лучшее, но вы также можете использовать -setValue: forKey:, хотя вам придется переключиться на использование NSNumbers, а не на int.

[theHighScores setValue: [NSNumber numberWithInt: mainScores.scoreTotal] forKey: [theHighScores findLowestHighScore]];
1 голос
/ 18 декабря 2009

Если бы я был на вашем месте, я бы использовал вместо этого изменяемый массив, чтобы позволить сортировку и легко выделить самый низкий элемент.

///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];
}
0 голосов
/ 18 декабря 2009

Звучит так, будто вы пытаетесь провести базовый самоанализ типа . В частности, используя NSSelectorFromString .

int newValue = 1;
SEL methodName = NSSelectorFromString(@"setHighScore03:");
[theHighScores performSelector:methodName withObject:newValue];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...