我已搜索周圍,找不到任何東西,將不勝感激。我對Objective-C和Xcode非常陌生。xcode - 當我更改視圖時,標籤更改值
在我的應用程序中,玩家以100個硬幣開始,這是用標籤表示的。當用戶點擊一個按鈕花費10個硬幣時,出現一個彈出框並詢問'你確定',用戶可以點擊確定或取消。
如果用戶點擊「確定」,他們將花費10個硬幣。目前,在模擬器中,當我在相同的視圖中一切都很好,100下降到90等... 但是,當我去另一個視圖,然後再回來,硬幣數量回到100 。這與用戶退出應用程序時相同。
這裏是我的代碼:
.h文件中
//Coin
IBOutlet UILabel * coinCount;
.m文件
int coinAmount = 100;
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSLog(@"user pressed Cancel");
// Any action can be performed here
}
else
{
NSLog(@"user pressed OK");
coinAmount -= 10;
[coinCount setText:[NSString stringWithFormat:@"%d", coinAmount]];
NSString * string = [NSString stringWithFormat:@"%d", coinAmount];
//Save coin amount
NSString * saveCoinAmount = string;
NSUserDefaults * defaultsCoinAmount = [NSUserDefaults standardUserDefaults];
[defaultsCoinAmount setObject:saveCoinAmount forKey:@"saveCoinLabel"];
[defaultsCoinAmount synchronize];
}
}
這似乎保存新的硬幣量,所以現在當用戶轉到另一個視圖,然後我嘗試加載存儲的硬幣數量:
- (void)viewDidLoad
{
[super viewDidLoad];
//Coin Label
NSUserDefaults * defaultsLoadCoin = [NSUserDefaults standardUserDefaults];
NSString * loadCoinLabel = [defaultsLoadCoin objectForKey:@"saveCoinLabel"];
[coinCount setText:loadCoinLabel];
}
任何幫助將不勝感激!
你nsuserdefault保存價值和你的價值-10本地variable.you需要-10 nsuserdefult變量。 –