Frage

i am using NSUserDefaults to save a string in my app. It all works fine. But when i clear the cache/memory by pressing the homebutton twice, kill the app and restart it again the NSUserDefaults is not saved.

Is there a way to save the NSUserDefaults even when i clear cache/memory?

Here is the code i use:

To set the string

NSUserDefaults *savedString = [NSUserDefaults standardUserDefaults];
[savedString setObject:@"The string i want to save" forKey:@"savedString"];
[savedString synchronize];

To get the string

myLabel.text = [savedString stringForKey:@"savedString"];
War es hilfreich?

Lösung

In your AppDelegate.h file

+(NSUserDefaults*)getdefaultvalue;

In Your AppDelegate.m file

static NSUserDefaults *defaultvalue;

+(NSUserDefaults*)getdefaultvalue
{
    if (defaultvalue==nil)
    {
        defaultvalue=[NSUserDefaults standardUserDefaults];
        return defaultvalue;
    }
    return  defaultvalue;

}

In your class where you want to save data or string Ex.

[[AppDelegate getdefaultvalue] setObject:@"FacebookLogin" forKey:@"NORMALOGIN"];

Now Remove from apps and print the value of string in

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  NSLog(@" string == %@",[[AppDelegate getdefaultvalue] valueForKey:@"NORMALOGIN"]);

  Return YES;

}

You got String value.

Andere Tipps

Actually NSUserDefault save data in .plist, So when you remove you app then all data also get deleted.

Deleting the app will delete the plist file the NSUserDefaults generate. You will need to make a check if the files exists in your app, then load the UserDefaults if not, create the plist with the information. So you will have your standard settings when the user opens the app etc.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top