NSUserdefaults works on Simulator but not on Devic

2019-07-28 05:41发布

问题:

I would like to save an NSArray to NSUSerDefaults. If I do it on Simulator everything works, if I do it on Device, it doesnt work.

NSArray *Test1 = [Daten copy];
NSArray *Test2 = [Kosten copy];

[prefs setObject:Test1 forKey:@"Daten"];
[prefs setObject:Test2 forKey:@"Kosten"];

I am using the above code.

prefs is a normal NSUserDefaults, like NSUserDefaults *prefs = [NSUserDefaults standartUserDefaults];...

Daten & Kosten are Mutable Arrays, to work with.

Everything works on simulator, but on device it doesnt work...

Does anybody have an idea?

回答1:

Are you synchronizing them after settings/updating ?

[[NSUserDefaults standardUserDefaults] synchronize];


回答2:

Because Saurabh asked me to post my solution, I will do it for other readers.

My Problem Code was the following:

[derText1 resignFirstResponder]
[derText2 resignFirstResponder]

NSArray *Test1 = [Daten copy];
NSArray *Test2 = [Kosten copy];

[prefs setObject:Test1 forKey:@"Daten"];
[prefs setObject:Test2 forKey:@"Kosten"];

This worked on an iPhone 4 Simulator with XCode 3.2.5 but not on my Device with iOS 5.x installed.

So I have downloaded and installed the newest XCode version from Apple.

After that it also doesnt work with the Simulator too. It looks like the problem is only with iOS 5 Software.

Than I changed my code simply to that:

NSArray *Test1 = [Daten copy];
NSArray *Test2 = [Kosten copy];

[prefs setObject:Test1 forKey:@"Daten"];
[prefs setObject:Test2 forKey:@"Kosten"];

[derText1 resignFirstResponder]
[derText2 resignFirstResponder]

And it worked on Device and Simulator with the latest iOS. Take a look at the position of the resign First Responder Entrys. They seem to have to be after the saving. I don't know why, but it works.



回答3:

NSArray *Test1 = [Daten copy];<p>
NSArray *Test2 = [Kosten copy];<p>


NSUserDefaults *prefs;<p>
prefs= [[NSUserDefaults standardUserDefaults]setObject:Test1 forKey:@"Daten"];<p>

[[NSUserDefaults standardUserDefaults] synchronize];

prefs= [[NSUserDefaults standardUserDefaults]setObject:Test2 forKey:@"Kosten"];<p>

[[NSUserDefaults standardUserDefaults] synchronize];