2009-12-18 55 views
0

我有一系列5個iVar。 (highscore01,highscore02,highScore03,highScore04,highScore05)我想用一個整數值更新一個特定的iVar。 iVars被定義爲整數。 iVars在一個名爲HighScores的類中。字符串標識要更新的iVar

要更新的特定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;

任何有識之士將不勝感激。

回答

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]; 
} 
+0

感謝您的幫助。設置一個可變數組絕對是更好的方法。 – ReachWest 2009-12-18 23:01:20

1

我覺得mjdth的解決方案可能是最好的,但你也可以使用-setValue:forKey:,雖然你不得不改用NSNumbers,而不是整數。

[theHighScores setValue: [NSNumber numberWithInt: mainScores.scoreTotal] forKey: [theHighScores findLowestHighScore]]; 
0

聽起來你正在試圖做一些基本的type introspection。具體來說,使用NSSelectorFromString

int newValue = 1; 
SEL methodName = NSSelectorFromString(@"setHighScore03:"); 
[theHighScores performSelector:methodName withObject:newValue];