如何将整数值保存到NSuserDefault,如sqlite?

时间:2013-07-15 06:11:23

标签: iphone ios objective-c nsuserdefaults

我想在NSUserDefault中保存和检索值。我正在成功保存和检索价值。但是,当我去cak主页并再次进入我的班级时,不会存储该值,并且所有过程都会再次完成。它不记得旧的价值。

我这样做 -

-(void)ViewDidLoad{
    A = 0;                // int A; defone in .h
    [self calling_Once];
}

-(void)calling_Once{
     NSLog(@"A is: %d",A);     // A is always zero when I leave this class and return Back to this class. This is my only problem. I want A=1; when I go back And return to this class but 
     NSInteger B = [[NSUserDefaults standardUserDefaults] integerForKey:@"save_Interger_Value_For_Formula_One"];  //is not able to remeber value. It gives A=0; B =0; When I come back to this class, I want It should return A=1; B=1; and remember old value like sqlite when I return to this class.

     if (A==0) {
         [self refreshButton];
         NSLog(@"Before Increment A is: %d",A);
         A++;

         NSLog(@"After Increment A is: %d",A);

         [[NSUserDefaults standardUserDefaults] setInteger:A forKey:@"save_Interger_Value_For_Formula_One"];
    }

    NSInteger B = [[NSUserDefaults standardUserDefaults] integerForKey:@"save_Interger_Value_For_Formula_One"];
    B = A;

    NSLog(@" B is: %d",B);
    B = A;
    NSLog(@" A is: %d",A);
}

非常欢迎任何想法或建议。

4 个答案:

答案 0 :(得分:4)

保存整数;

[[NSUserDefaults standardUserDefaults] setInteger:number forKey:@"unique_name"];
[[NSUserDefaults standardUserDefaults] synchronize];

要检索它;

NSInteger x = [[NSUserDefaults standardUserDefaults] integerForKey:@"unique_name"];
祝你好运!

答案 1 :(得分:2)

尝试这样实现..确保它会有所帮助......

@implementation ClassA

- (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        [[NSUserDefaults standardUserDefaults]setInteger:100 forKey:@"save_Interger_Value_For_Formula_One"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

@end

@implementation ClassB

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
       int B = [[[NSUserDefaults standardUserDefaults]        integerForKey:@"save_Interger_Value_For_Formula_One"] integerValue];

     NSLog(@"Interger Value %d",b);
}

答案 2 :(得分:0)

插入值后,只需synchronize NSUserDefaults

[[NSUserDefaults standardUserDefaults] synchronize];  

您可以按照此回答How to delete a user default value in NSUserDefaults?

在您的代码中,您最初将0设置为A,请尝试此

-(void)ViewDidLoad
{
        A = [[NSUserDefaults standardUserDefaults] integerForKey:@"save_Interger_Value_For_Formula_One"];   
      [self calling_Once];
}

答案 3 :(得分:0)

NSUserDefaults * def=[NSUserDefaults standardUserDefaults];
    [def setInteger:yourvalue forKey:@"YourKey"];
    [def synchronize];

试试这个代码......