【发布时间】:2014-06-14 08:43:11
【问题描述】:
我四处寻找,找不到任何东西,不胜感激。我对 Objective-C 和 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。您需要 -10 nsuserdefult 变量。
标签: ios objective-c xcode