保存UILabel信息?

时间:2013-04-20 13:02:06

标签: ios objective-c save

我正在为我的应用程序进行下一次更新,我正在尝试在应用关闭或切换页面时将信息保存在我的UILabel上。这就是我所拥有的,每次按下一个按钮,它都会更新我的UILabel,将前一个数字加1,即值= 0,但按下按钮= 1,但每次重新加载页面时似乎重置,我我们想知道他们是否是保存这些信息的一种方式,如果是这样,你怎么能这样做?以下是我的一些代码。

标头文件

//Here I have created two labels that get updated when button pressed.
IBOutlet UILabel *label1;
IBOutlet UILabel *label2;

}
//Here I have created two variables that correspond to the change in number.
@property (nonatomic) int i;
@property (nonatomic) int s;

实施档案:

//Here I have instantiated the two variables in my viewWillAppear method.
- (void)viewWillAppear{

self.i = 0;
self.s = 0;

}

//Here I have my button that changes the value of the label.
-(IBAction)randomButton {

self.i++;
[self->label1 setText:[NSString stringWithFormat:@"%d", self.i]];

先谢谢了。回顾:如何保存我的UILabel的值,但是当按下按钮时,通过在值上加1来允许它们仍然更新?但是我希望能够保存这个价值并回归它。任何帮助将不胜感激。

更新: 第1页(这是我的主页)

enter image description here

第2页(我的统计页面/游戏页面)

enter image description here

我希望能够保存这个号码,这是一个UILabel。然而,当我玩一点并获得高数字,然后按回第二页的左上角,然后按第一页上的开始agian,数字恢复为0.我怎样才能让它们保持价值?

以下是我的问题(在.h中): enter image description here

以下是我的问题(在.m中): enter image description here

再次更新:我的.h现在没有问题,但我的.m有很多: enter image description here

这是我的AppDelegate.h enter image description here

2 个答案:

答案 0 :(得分:1)

编辑您的AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

//add thist 2 properties
@property (nonatomic, assign) NSUInteger counti;
@property (nonatomic, assign) NSUInteger counts;

@end

然后编辑viewcontroller的代码

- (void)viewWillAppear:(BOOL)animated{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    [self->label1 setText:[NSString stringWithFormat:@"%d", appDelegate.counti]];
    [self->label2 setText:[NSString stringWithFormat:@"%d", appDelegate.counts]];
}

-(IBAction)randomButton {

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    appDelegate.counti = appDelegate.counti+1 ;
    [self->label1 setText:[NSString stringWithFormat:@"%d", appDelegate.counti]];


}

它应该有用

答案 1 :(得分:1)

使用NSUserDefaults有什么问题吗?这样,它将在视图和应用关闭时保存。

添加以下按钮操作:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setValue:aValue forKey:@"savedString1];

第一行是快速访问。然后将值(aValue)存储在“savedString1”字符串下。

然后,根据您希望再次加载的时间,您可以执行以下操作:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *returnAValue = [userDefaults valueForKey:@"savedString1"];

然后,这将声明具有先前值的新NSString。您可以在viewDidLoad中包含它。

你也可以存储整数/其他东西 - 加载时只需使用integerForKey而不是valueForKey,并声明一个整数。

希望有帮助吗?