I am doing a project where I have to retrieve some values in settings.bundle. For this I have to retrieve a default value in such a manner.
I am accessing it as under
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
stringObject = [defaults objectForKey:#"Key_Value"];
But when I try to print stringObject
NSLog(#"%#",stringObject);
Then it always print null.
I have saved a string value in the settings.bundle with key "Key_Value". But It returns Null.
tell me where I am doing wrong
check you have stored you value in this way:-
NSUserDefaults *pref3=[NSUserDefaults standardUserDefaults];
[pref3 setObject:*yourstring* forKey:#"Key_Value"];
[NSUserDefaults resetStandardUserDefaults];
your code of retreiving is correct.make sure stringObject is of NSString type.
Call this function will resolve your issue
- (void)registerDefaultsFromSettingsBundle {
// this function writes default settings as settings
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
if(!settingsBundle) {
NSLog(#"Could not find Settings.bundle");
return;
}
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:#"Root.plist"]];
NSArray *preferences = [settings objectForKey:#"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:#"Key"];
if(key) {
[defaultsToRegister setObject:[prefSpecification objectForKey:#"DefaultValue"] forKey:key];
NSLog(#"writing as default %# to the key %#",[prefSpecification objectForKey:#"DefaultValue"],key);
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
}
Related
+(NSString *)languageKey{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:#"AppleLanguages"];
NSString *lang = [languages objectAtIndex:0];
if([lang isEqualToString:#"en"])
return #"en";
else if([lang isEqualToString:#"ar"])
return #"ar";
return #"en";
}
+(NSString *)localizedStringForKey:(NSString *)key{
NSString *path;
if([[self languageKey] isEqualToString:#"en"])
path = [[NSBundle mainBundle] pathForResource:#"en" ofType:#"lproj"];
else if([[self languageKey] isEqualToString:#"ar"])
path = [[NSBundle mainBundle] pathForResource:#"ar" ofType:#"lproj"];
NSBundle* languageBundle = [NSBundle bundleWithPath:path];
NSString* str=[languageBundle localizedStringForKey:key value:#"" table:nil];
return str;
}
Sometimes i am getting wrong key here in iOS7 and below version working fine. Is this Xcode6.0 bug?
How to get rid of this issue
Advance Thanks
well Objective-C and Xcode-6 works fine with UserDefaults, in my experience with NSUserDefaults you need to be very careful with the way you save and retrieve data:
I Save data like this:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:#"data" forKey:#"key"];
[prefs synchronize];
And i retrieve data like this:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *theString = [prefs stringForKey:#"key"];
I Also see a [defaults synchronize] when you are retrieving the data, I think that is not necessary because you aren´t saving data, good luck.
I’m trying to save a NSMutableDictionary with NSUserDefaults. I read many posts on the topic in stackoverflow... I also found one option that worked; however unfortunately it worked only once and then it started to save (null) only.
Does anybody have a hint?
Thanks
Code to save:
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dictionary] forKey:#"Key"];
[[NSUserDefaults standardUserDefaults] synchronize];
Code to load:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:#"Key"];
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Code to add Objects to the NSMutableDictionary:
[dictionary setObject:[NSNumber numberWithInt:0] forKey:#"Key 1"];
[dictionary setObject:[NSNumber numberWithInt:1] forKey:#"Key 2"];
[dictionary setObject:[NSNumber numberWithInt:2] forKey:#"Key 3"];
Code to NSLog() values:
for (NSString * key in [dictionary allKeys]) {
NSLog(#"key: %#, value: %i", key, [[dictionary objectForKey:key]integerValue]);
}
And also the keys are (null):
NSLog(#"%#"[dictionary allKeys]);
From Apple's documentation for NSUserDefaults objectForKey:
The returned object is immutable, even if the value you originally set was mutable.
The line:
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
discards the previously created NSMutableDictionary and returns a NSDictionary.
Change the loading to:
NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:#"Key"];
dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Complete example, there is also no need to use NSKeyedArchiver in this example:
NSDictionary *firstDictionary = #{#"Key 4":#4};
[[NSUserDefaults standardUserDefaults] setObject:firstDictionary forKey:#"Key"];
NSMutableDictionary *dictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:#"Key"] mutableCopy];
dictionary[#"Key 1"] = #0;
dictionary[#"Key 2"] = #1;
dictionary[#"Key 3"] = #2;
for (NSString * key in [dictionary allKeys]) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}
NSLog output:
key: Key 2, value: 1
key: Key 1, value: 0
key: Key 4, value: 4
key: Key 3, value: 2
I have a plist file which is an array of dictionaries. Where each dictionary contains a set of strings. Each dictionary represents a celebrity.
What I would like to do is populate Core Data with the contents of this plist on the applications first launch, after which I would like to somehow check core data for the existence of my data, and if there is data, load it from there, otherwise load the initial data from the plist file again.
I know its possible to populate core data from a plist, but is what I'm suggesting a viable solution? Or is there a better approach?
Jack
My sample code
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"dataImported"]) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"dict" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
for (NSString *key in [dict allKeys]) {
NSDictionary *node = [dict objectForKey:key];
MyClass *newObj = .....
}
[defaults setObject:#"OK" forKey:#"dataImported"];
[defaults synchronize];
}
This is doing the same thing but with a slightly more complex pList that contains an array of dictionaries representing data on a "topic" to be stored. It still has some of the debug logging in place. Hope it is useful to someone.
NSManagedObjectContext *context = self.managedObjectContext;
NSError *error;
NSFetchRequest *topicRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *topicEntityDescription = [NSEntityDescription entityForName:#"Topic" inManagedObjectContext:context];
[topicRequest setEntity:topicEntityDescription];
NSManagedObject *newTopic = nil;
NSArray *topics = [context executeFetchRequest:topicRequest error:&error];
if (error) NSLog(#"Error encountered in executing topic fetch request: %#", error);
if ([topics count] == 0) // No topics in database so we proceed to populate the database
{
NSString *topicsPath = [[NSBundle mainBundle] pathForResource:#"topicsData" ofType:#"plist"];
NSArray *topicsDataArray = [[NSArray alloc] initWithContentsOfFile:topicsPath];
int numberOfTopics = [topicsDataArray count];
for (int i = 0; i<numberOfTopics; i++)
{
NSDictionary *topicDataDictionary = [topicsDataArray objectAtIndex:i];
newTopic = [NSEntityDescription insertNewObjectForEntityForName:#"Topic" inManagedObjectContext:context];
[newTopic setValuesForKeysWithDictionary:topicDataDictionary];
[context save:&error];
if (error) NSLog(#"Error encountered in saving topic entity, %d, %#, Hint: check that the structure of the pList matches Core Data: %#",i, newTopic, error);
};
}
Icstored the value of 2 label in NSUserDefault, trought NSMutableArray.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:author.text forKey:#"author"];
[bookmark setValue:book.text forKey:#"book"];
[bookmarks addObject:bookmark];
// Save your (updated) bookmarks
[userDefaults setObject:bookmarks forKey:#"bookmarks"];
[userDefaults synchronize];
Now my problem is how retrieve the values of NSUserDefault trought NSArray?
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [prefs arrayForKey:#"bookmarks"];
NSString *author = ??
NSString *book = ??
NSString * author = [self.dataArray objectForKey: #"author"];
NSString * book = [self.dataArray objectForKey: #"book"];
This assumes you successfully saved the array and that you successfully re-loaded the array from NSUserDefaults. You really should do some error checking in your code.
In the dataArray, you can store lots of bookmarks.This methods can log all of the bookmarks.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [prefs objectForKey:#"bookmarks"];
for(int i=0;i<[dataArray count];i++){
NSDictionary *dic = [dataArray objectAtIndex:i];
NSLog(#"%#",dic);
NSString * author = [dic objectForKey: #"author"];
NSString * book = [dic objectForKey: #"book"];
}
you have inserted an array with a dictionary. you can retrieve it by using
self.dataArray = [prefs arrayForKey:#"bookmarks"];
NSString *author = [self.dataArray objectAtIndex:0] objectForKey:#"author"];
NSString *book = [self.dataArray objectAtIndex:0] objectForKey:#"book"];
But it is better to store the dictionary directly in user defaults.
I am building this 'Add to favorite' with NSUserDefault. I am having this issue when adding array to NSMutableArray. Does anyone knows what I did wrong? Thank you very much.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *favoriteRecipes = [[NSMutableArray alloc] init];
if ([prefs objectForKey:#"myFavor"] == nil) {
//create the array
NSMutableArray *array = [[NSMutableArray alloc] init];
[prefs setObject:array forKey:#"myFavor"];
[array release];
}
NSMutableArray *tempArray = [[prefs objectForKey:#"myFavor"] mutableCopy];
favoriteRecipes = tempArray;
[tempArray release];
NSArray *charArray = [[NSArray alloc] initWithObjects: #"test1", #"test2" , nil];
//add the recipe
[favoriteRecipes addObject:[charArray objectAtIndex:0]];
//save the array to NSUserDefaults
[prefs setObject:favoriteRecipes forKey:#"myFavor"];
[prefs synchronize];
favoriteRecipes = tempArray;
instated of above line use be below line it will work fine
[favoriteRecipes addObjectsFromArray:tempArray];
done something like this yesterday. see my code below. im not sure if you want the same thing like I did.
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjectsAndKeys:productID,#"ID",productTitle,#"title",productPrice,#"price",imageUrl,#"image",shipping,#"shipping_day", nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *cartList = [[defaults objectForKey:#"CART_ITEMS"] mutableCopy];
if(!cartList)
cartList = [[NSMutableArray alloc] init];
if([cartList indexOfObject:tempDictionary] == NSNotFound)
{
NSLog(#"add favorite");
[cartList addObject:tempDictionary];
[defaults setObject:cartList forKey:#"CART_ITEMS"];
[defaults synchronize];
[sender setTitle:#"Remove" forState:UIControlStateNormal];
}
else
{
NSLog(#"remove favorite");
[cartList removeObject:tempDictionary];
[defaults setObject:cartList forKey:#"CART_ITEMS"];
[defaults synchronize];
[sender setTitle:#"Add to cart" forState:UIControlStateNormal];
}
this is what I do everytime I want my favorite list from NSUserDefault
-(void)getCartList
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *cartList = [[defaults objectForKey:#"CART_ITEMS"] mutableCopy];
productListArr = [NSMutableArray arrayWithArray:cartList];
NSLog(#"cart list data == %#", cartList);
}