2014-08-27 75 views
0

在我的板子結束,我要救的水平,局分,併成一個總NSUserDefaults的點,再回想,打破數字退了出去。這可能嗎?試圖不要每次都有一個NSUserDefaults列表。如何用一個NSUserDefaults保存多個數字?

例子:

int level = 35 
int boardPoints = 500 
int totalPoints = 18000 

我想保存「levelValue」與所有三個,也許有一段時間分隔符? levelValue = 35.500.18000;

// Save value 
[[NSUserDefaults standardUserDefaults] setObject:levelValue forKey:@"levelValueKey"]; 
[[NSUserDefaults standardUserDefaults] synchronize]; 

// Recall 
// Somehow recall Left(levelValueKey,2), Mid(starting from period,2), and right(up to period) 
level = [[NSUserDefaults standardUserDefaults] objectForKey:@"levelValueKey"]; 
boardPoints = [[NSUserDefaults standardUserDefaults] objectForKey:@"levelValueKey"]; 
totalPoints = [[NSUserDefaults standardUserDefaults] objectForKey:@"levelValueKey"]; 

有什麼想法?

回答

2

保存所有你整數作爲一個NSArray在NSUserDefaults的,而不是像這樣:

//your ints 
int level = 35; 
int boardPoints = 500; 
int totalPoints = 18000; 

//put ints in array 
NSArray *levelValueArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:level], [NSNumber numberWithInt:boardPoints], [NSNumber numberWithInt:totalPoints], nil] 
//save in NSUserDefaults 
[[NSUserDefaults standardUserDefaults] setObject:levelValueArray forKey:@"levelValueKey"]; 

//retreive 
NSArray *arrayLevelValues = [[NSUserDefaults standardUserDefaults] objectForKey:@"levelValueKey"]; 

使用它們:

NSLog(@"arrayLevelValues: %@", arrayLevelValues[1]); 
//the object 1 is a string so you'll need to convert it to int using intValue 
int tempPoints = [arrayLevelValues[1] intValue]; 
NSLog(@"tempPoints: %d",tempPoints); 
+0

我得到了兩個錯誤:NSArray的* levelValueArray = [NSArray的arrayWithObjects:水平,boardPoints,totalPoints,零];不兼容的整數指針轉換髮送「廉政」類型爲「ID」和「詮釋」到「身份證」的隱式轉換的參數是不允許與ARC – user1467534 2014-08-28 15:10:34

+0

@ user1467534是我不好,看我更新的答案 – tnylee 2014-08-28 15:17:45

+0

這一工程完美!我正在嘗試檢索單個值。第一個NSLog的作品,但我不知道如何保存價值? NSLog(@「arrayLevelValues:%@」,arrayLevelValues [1]); int tempPoints = arrayLevelValues [1]; 的NSLog(@ 「tempPoints:%d」,tempPoints);此外,我使用的一個NSInteger爲64位,將其效果的NSNumber陣列中? – user1467534 2014-08-28 15:33:31

相關問題