简体   繁体   English

更新UILabel返回Null吗?

[英]Updating UILabel Returns Null?

I'm trying to update a label that display the amount of coins, stored in NSUserDefaults . 我正在尝试更新一个标签,该标签显示存储在NSUserDefaults的硬币NSUserDefaults

I have a method called updateCoins which I call when I have added, coins based on user activity, to update the UILabel : 我有一个称为updateCoins的方法,添加后会调用该方法,它基于用户活动来更新UILabel

- (void)updateCoins {
    self.coinsLabel.text = 
     [NSString stringWithFormat:@"%d", 
       [[[NSUserDefaults standardUserDefaults] objectForKey:@"Coins"] intValue]];
    NSLog(@"Label: %@", self.coinsLabel.text);
    NSLog(@"Coins: %d", 
       [[[NSUserDefaults standardUserDefaults] objectForKey:@"Coins"] intValue]);
}

However in the logger, I get the following: 但是,在记录器中,我得到以下信息:

Label: (null)
Coins: 10

The thing is when, I call this method in viewWillAppear , it updates the app, when transitioning to a different UIViewController and coming back. 问题是,当我在viewWillAppear调用此方法时,它会在过渡到其他UIViewController并返回时更新应用程序。

If it helps I'm updating the object the following way: 如果有帮助,我可以通过以下方式更新对象:

int coins;
coins = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Coins"] intValue];
[[NSUserDefaults standardUserDefaults] setObject:
  [NSString stringWithFormat:@"%d",coins+10] forKey:@"Coins"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self updateCoins];
self.coinsLabel.text = // replace this with self.treeCoinsLabel.text
 [NSString stringWithFormat:@"%d", 
  [[[NSUserDefaults standardUserDefaults] objectForKey:@"Coins"] intValue]];
NSLog(@"Label: %@", self.treeCoinsLabel.text);

Also if your self.coinsLabel is an outlet, verify that it's correctly connected on the user interface, if not you must allocate it before use it. 另外,如果self.coinsLabel是插座,请验证它是否在用户界面上正确连接,否则请在使用前进行分配。

Hopefully, you are assigning the value to the self.coinsLabel.text before its get allocated (pointer which holds other custom UILabel) , that's why it gets updated when come back from the child UIViewController. 我们希望,你是分配值到self.coinsLabel.text其获得分配 (指针持有其他自定义的UILabel)之前,这是来自孩子的UIViewController回来时,它为什么被更新。

Ensure that the UILabel has allocated before assign the value to it. 在分配值之前,请确保已分配UILabel you might calling this function before the View gets loaded. 您可以在加载视图之前调用此函数。

There are two possibilities in this situation. 在这种情况下有两种可能性。

self.coinsLabel is null and not initialized. self.coinsLabel为null且未初始化。 If self.coinsLabel = [[UILabel alloc] init]; 如果self.coinsLabel = [[UILabel alloc] init]; doing this in - (void)viewDidLoad is still nill then you should check Is it connected from storyboard to class? - (void)viewDidLoad仍然为零,那么您应该检查Is it connected from storyboard to class? .

- (void)viewDidLoad:animated
{
    [super viewDidLoad:animated];
    self.coinsLabel = [[UILabel alloc] init];
}

I guess you forget initializing UILabel. 我猜您忘了初始化UILabel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM