Reading String With NSUserDefaults not working - ios

I'm using iOS9 SDK, and I'm trying to read a string using :
NSString *savedID = [[NSUserDefaults standardUserDefaults] stringForKey:#"ID"];
I saved it using :
[[NSUserDefaults standardUserDefaults] setObject:[myPeripheral.identifier UUIDString] forKey:#"ID"];
[[NSUserDefaults standardUserDefaults] synchronize];
The problem is that the property savedID has a nil value.
When I execute the ligne bellow in the consol, I get the value I saved :
po [[NSUserDefaults standardUserDefaults] stringForKey:#"ID"];
PS : The value I saved is : 73BAE46D-3A74-E7F4-05F7-EFCB6AACC20C
I also tried to use objectForKey, but I still got the same result.
Any Idea?

I was debugging on a device, I tried to execute the App without debug and it worked :p
Thank you every one.

Related

How to save a high score

How do I go about saving a high score using nsuserdefaults and displaying it on the main menu. Currently my score label code looks like this. BTW I am using objective c.
_scoreLabel.text = [NSString stringWithFormat:#"%02lu", (unsigned long)_enemies.count];
this is how you save the score
if(HighScore<ScoreNumber)
{
[[NSUserDefaults standardUserDefaults]setInteger:ScoreNumber forKey:#"Save"];
}
this is how you get the score,so you need to convert int to string..and display a string in a label.
HighScore=[[NSUserDefaults standardUserDefaults] integerForKey:#"Save"];
You can save your highScore using NSUserDefaults setInteger. The code for saving an integer into NSUserDefault goes here.
[[NSUserDefaults standardUserDefaults] setInteger:HighScore forKey:#"HighScore"];
Now you can set the highScore from NSUserDefault. The code for retrieving Integer from NSUserDefault goes here.
[_scoreLabel setText:[NSString stringWithFormat:#"%d", [[NSUserDefaults standardUserDefaults] integerForKey:#"HighScore"]]];

Xcode: I Can't Set an NSUserdefault to itself + 5

This is for iOS
[[NSUserDefaults standardUserDefaults] integerForKey:#"money"] =
[[NSUserDefaults standardUserDefaults] integerForKey:#"money"] + 5;
Could Someone Please Help Me With This, I'm Getting This Error:
Assigning to 'readonly' return result of an Objective-C message not allowed
integerForKey is a getter method. used setInteger setter method for setting property like as bellowed.
[[NSUserDefaults standardUserDefaults] setInteger:[[NSUserDefaults standardUserDefaults] integerForKey:#"money"] + 5 forKey:#"money"];
Hope this help you.

How I can make NSUserDefaults for each user of my app?

I need make access to UserDefaults in my app. But I need save settings for each user, who was registered in app. For example:
[[NSUserDefaults standartUserDefaults] setObject:#"15:00" forKey:#"lastTime"]// for current user1
and after logout user1 and login user2:
[[NSUserDefaults standartUserDefaults] setObject:#"11:00" forKey:#"lastTime"]// for current user2
And, if I try read key #"lastTime", then I get the last value, but not for this user. I can store userDefaults in differentFiles, as an a variant? Or other solutions?
UPDATED:
Finally I solved this problem:
#define UserDefaults [NSUserDefaults standardUserDefaults]
#define uKey(key) [NSString stringWithFormat:#"%#_%#",key,User.user_name]
[UserDefaults setInteger:lastData forKey:uKey(#"lastResultDataId")];
There is no concept of users on iOS (yet). Each device, an iPhone or iPad, is presumed to have one and only one user. Obviously that's often not true, especially on an iPad, so some apps create schemes for different people to use the device. If you've done that -- and it's not clear that you have -- then you know the username. If you are writing a Mac app then use NSUserName() to get the name of the logged-in user. After that just concatenate the username onto the key from your NSUserDefaults, something like this:
NSString *username = #"john";
[[NSUserDefaults standardUserDefaults] setObject:#"15:00" forKey:[NSString stringWithFormat:#"last_login_username_%#", username]];
(username would set either to NSUserName() for a Mac app or whatever scheme you've come up for a multiuser iOS app)
If you have some kind of user identifier, use a dictionary for the different users:
NSDictionary *user = #{#"lastTime": #"15:00" };
[[NSUserDefaults standartUserDefaults] setObject:user forKey:#"userId"];
You have to have some way to uniquely identify the user, then just use whatever that is - UUID, username, email, userId - in the key when setting / getting the lastTime value
Personally I'd use a NSDictionary like and have a dictionary per user and store that into NSUserDefaults under a key constructed out of their username similar to below.
NSMutableDictionary *userDict = [[NSMutableDictionary alloc] init];
NSString *username = "myUsername";
NSDate *currentDateTime = [NSDate date];
[userDict setObject:username forKey:#"username"];
[userDict setObject:currentDateTime forKey:#"lastAccessed"];
/* Any other user date you want to store about this user
* Note we are going to use NSUserDefaults which is not
* secure so do not store sensitive data in here
*/
NSString *userDictKey = [NSString stringWithFormat:#"uk.co.yourAppName.%#", username];
[[NSUserDefaults standardUserDefaults] setObject:userDict forKey:userDictKey];
[[NSUserDefaults standartUserDefaults] synchronize];
And to retrieve this data all you'd need to do is know what the users username is and do
NSString *userDictKey = [NSString stringWithFormat:#"uk.co.yourAppName.%#", username];
NSDictionary *userRetrievedDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:userDictKey];
However if you want to make any amendments to this data you'll need to adapt it so that the data is moved into a NSMutableDictionary so you can update it and then store it back into NSUserDefaults
Make sure that after setting value, user going to synchronise the userdefaults.
like
[[NSUserDefaults standartUserDefaults] synchronize];

NSUserDefaults. Retrieving incorrect values

I am saving few dictionaries in NSUserDefaults this way:
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"event_states"] == nil)
{
NSDictionary *dict0 = [NSDictionary dictionaryWithObjectsAndKeys:
#"923381DC-3DCB-46CA-A6CF-C58A7AF33B89",#"guid",
#"В планах",#"name", //this string will returned corrupted
[NSNumber numberWithInt:12632256],#"color",
[NSNumber numberWithInt:0],#"isclosed",
[NSNumber numberWithInt:0],#"isfinish",
nil];
// and few more dictionaries same way
....
[[NSUserDefaults standardUserDefaults] setObject:#[dict0,dict1,dict2,dict3] forKey:#"event_states"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NSArray *event_states = [[NSUserDefaults standardUserDefaults] objectForKey:#"event_states"];
When I am retrieving this data I am logging it and have a strange behavior. In some cases I am retrieving a correct value as this:
name = "\U0412 \U043f\U043b\U0430\U043d\U0430\U0445"
but in some cases as this:
name = "\U0412\U044b\U043f\U043e\U043b\U043d\U0435\U043d(\U043e)
and this last part in parenthesis is an extra symbol and I can't understand why it appears and what is dependence on when it appears and when it's not. What can be wrong with this?
I tried to convert your unicode to readable string and paste it in google translate
\U0412 \U043f\U043b\U0430\U043d\U0430\U0445 => В планах => The plans
\U0412\U044b\U043f\U043e\U043b\U043d\U0435\U043d(\U043e) => Выполнен(о) => Complete ?
So I think this happened because your code not the API.

How to set initial values for NSUserDefault Keys?

I want to set some initial values for my NSUserDefault keys so that the first run of the app has some reasonable initial settings. I thought I ran across a simple way to do this in the app bundle .plist, but now I can't find it. Any ideas?
You should use the registerDefaults method of NSUserDefaults. Prepare a plist file in your bundle that contains the default preferences and then use that plist to register the defaults.
NSString *defaultPrefsFile = [[NSBundle mainBundle] pathForResource:#"defaultPrefs" ofType:#"plist"];
NSDictionary *defaultPreferences = [NSDictionary dictionaryWithContentsOfFile:defaultPrefsFile];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPreferences];
You have to execute this code on every launch of your app. It will add these values to a separate domain in the user defaults hierarchy. Whenever your app's user defaults don't provide a value for a certain key, NSUserDefaults will fall back to this domain and retrieve the value from there.
If you have many default values, let use ola's answer, otherwise this is good for a few params
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:USERDEFAULT_IS_INITIALIZED]) {
[defaults setBool:YES forKey:USERDEFAULT_IS_INITIALIZED];
// Set initial values
...
[defaults synchronize];
}
if ([[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys] containsObject:#"initialValuesHaveBeenWritten"])
{
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:key1];
[[NSUserDefaults standardUserDefaults] setValue:obj2 forKey:key2];
[[NSUserDefaults standardUserDefaults] setValue:obj1 forKey:#"initialValuesHaveBeenWritten"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
NB: Not tested, done from memory
-(void) loadDef
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
_removeAd=[userDefaults boolForKey:SAVE_AD_STATUS];
NSString* strDefSetting=[userDefaults stringForKey:SAVE_STATUS_ADSETTING];
if(strDefSetting==nil
||[strDefSetting isEqualToString:#""]
)
{
strDefSetting=#"0.5";
}
_floatAdmob=strDefSetting.floatValue;//0.5;
}

Resources