2014-06-14 105 views
0

我已搜索周圍,找不到任何東西,將不勝感激。我對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]; 

} 

任何幫助將不勝感激!

+0

你nsuserdefault保存價值和你的價值-10本地variable.you需要-10 nsuserdefult變量。 –

回答

1

你的問題是,你存儲在兩個地方你的硬幣 - 一個整型變量和標籤。當您返回到您的視圖時,您將存儲的硬幣數量直接恢復到標籤中,但是當您執行「購買」時,將使用已重新初始化爲100的整數。

我也建議您退出習慣使用實例變量並使用屬性。

你應該做這樣的事情 -

.m文件

@interface MyClass()    // Change this to suit your class name 

@property NSInteger coinAmount; 
@property (weak,nonatomic) IBOutlet UILabel *coinLabel; 

@end 


@implementation MyClass 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
//Coin Label 
    NSUserDefaults * defaultsLoadCoin = [NSUserDefaults standardUserDefaults]; 
    if ([defaultsLoadCoin objectForKey:@"coins] == nil) { 
     self.coinAmount=100; 
     [defaultsLoadCoin setInteger:self.coinAmount forKey:@"coins"]; 
    } 
    else { 
     self.coinAmount = [defaultsLoadCoin integerForKey:@"coins"]; 
    } 

    self.coinLabel.text=[NSString stringWithFormat:@"%ld",self.coinAmount]; 

} 

- (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"); 

    self.coinAmount -= 10; 
    self.coinLabel.text=[NSString stringWithFormat:@"%ld",self.coinAmount]; 

    //Save coin amount 
    NSString * saveCoinAmount = string; 
    NSUserDefaults * defaultsCoinAmount = [NSUserDefaults standardUserDefaults]; 
    [defaultsCoinAmount setInteger:self.coinAmount forKey:@"coins"];; 
    [defaultsCoinAmount synchronize]; 
} 
0

您的coinAmount屬性不會通過應用程序啓動或其創建的view controller的初始化持久化。您應該考慮在數據庫中保留該值(如CoreData)或NSUserDefaults

我的建議是:與基礎開始(鏈接文檔):

CoreData

NSUserDefaults