当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - How would I be able to save an integer when an app is terminated and then load it again once the app is reopened?

问题描述:

I am working on an app where I need to save one int until the player decides to play the game again. It would be greatly appreciated if someone could guide me by using NSUserDefaults to save this integer whenever the application is terminated, and then be able to load it again as soon as the application loads. If there is any further information that is needed to help you help me just let me know! Thanks in advance!

网友答案:

You cannot save an int, you will need to convert it to an NSNumber. Use:

 NSNumber *number = @(myInt);

Then you can save it (when the app terminates in your appDelegate's applicationWillTerminate:) using:

[[NSUserDefaults standardUserDefaults] setObject:number forKey:@"number"];
[[NSUserDefaults standardUserDefaults] synchronize];

To retrieve the value use:

NSNumber *number = [[NSUserDefaults standardUserDefaults] stringForKey:@"number"];
网友答案:

As pranav told you can store int as NSNumber or you can store it as a String, Following will work fine with NSNumber object,

    int a = 10;
    NSNumber *myNumber = [NSNumber numberWithInt:a];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:myNumber forKey:@"storedInt"];
    NSLog(@"stored number object %@", [defaults objectForKey:@"storedInt"]);//retive value from NSUserDefaults

    //then change NSNumber object to int value - if required
    int retrivedInt = [myNumber intValue];
    NSLog(@"int value %u", retrivedInt);
分享给朋友:
您可能感兴趣的文章:
随机阅读: