2014-05-20 36 views
0

我試圖用NSUserDefaults這樣來增加NSIntegerNSUserDefaults的不遞增

NSInteger attempts = [[NSUserDefaults standardUserDefaults]integerForKey:@"tries"]; 
NSInteger newA = attempts++; 
[[NSUserDefaults standardUserDefaults]setInteger:newA forKey:@"tries"]; 
[[NSUserDefaults standardUserDefaults]synchronize]; 
NSLog(@"Tries: %d",[[NSUserDefaults standardUserDefaults]integerForKey:@"tries"]); 

但是這是我的NSLogs

Tries: 0 
Tries: 0 
Tries: 0 
+0

你發起了嗎? – EridB

+0

在64位系統上,'NSInteger'可能無法正確使用'%d'。嘗試'NSLog(@「試驗:%d」,(int)[[NSUserDefaults standardUserDefaults] integerForKey:@「試試」]);' – dasblinkenlight

回答

7

這是你的問題

NSInteger newA = attempts++; 

你在將它設置爲newA之後嘗試增加嘗試次數,請嘗試此嘗試廣告:

NSInteger newA = ++attempts; 
+0

好的。 (投票)我最初錯過了 –

+0

爲什麼'NSInteger newA = attempts + 1;'是一個更好的方法,它沒有額外的語義,比如pre vs post post。甚至只需更新'attempts':'attempts + = 1;'並跳過'newA'。 – zaph