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);
}
Related
I have UIWebview for display article. I need to select some text and send to another viewcontroller UITextView. But when i install the app i select text and it loads to viewcontroller1. But then i select another some text when i go to viewcontroller1, the previous text only showing. It's not updating new text.
code:
viewcontroller:
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:selection forKey:#"preferenceName"];
[userData1 synchronize];
[self.navigationController pushViewController:viewcontroller1 animated:YES];
viewcontroller1:
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferenceName"];
textView.text = [NSString stringWithFormat:#"%#", savedValue];
[self.view addSubview:textView];
in your viewcontroller1 try to do it like this
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
NSString *savedValue = [userData1 valueForKey:#"preferenceName"];
textView.text = [NSString stringWithFormat:#"%#", savedValue];
[self.view addSubview:textView];
Try this :
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setValue:selection forKey:#"preferenceName"];
[NSUserDefaults standardUserDefaults] synchronize];
[self.navigationController pushViewController:viewcontroller1 animated:YES];
//View controller
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
valueForKey:#"preferenceName"];
UITextView *textView = [UITextView alloc] initWithFrame : cgRectMake(0,0,200,50)]//if not created textview
[self.view addSubview:textView];
textView.text = [NSString stringWithFormat:#"%#", savedValue];
I have UIWebView for reading content. After that i select some text from content stores in string using NSUserDefaults in Viewcontroller. Then i retrieve this string value and displays in UITextView to viewcontroller1. But the UITextView is not updating text from viewcontroller. The NSUserDefaults also not getting updating text. Im using [self.navigationController pushViewController:viewcontroller1 animated:YES]; for switch to viewcontroller1.
viewcontroller:
[wbCont loadHTMLString:webString baseURL:nil];
[self.view addSubview:wbCont];
NSMutableArray *items = [[[UIMenuController sharedMenuController] menuItems] mutableCopy];
if (!items) items = [[NSMutableArray alloc] init];
UIMenuItem *menuItem;
menuItem = [[UIMenuItem alloc] initWithTitle:#"BookMark" action:#selector(save:)];
[items addObject:menuItem];
[menuItem release];
menuItem = [[UIMenuItem alloc] initWithTitle:#"Note" action:#selector(note:)];
[items addObject:menuItem];
[menuItem release];
[[UIMenuController sharedMenuController] setMenuItems:items];
[items release];
- (BOOL) canPerformAction:(SEL)action withSender:(id)sender
{
if (action == #selector(save:))
{
return YES;
}
else if (action == #selector(note:))
{
return YES;
}
else if (action == #selector(copy:))
{
return NO;
}
return [super canPerformAction:action withSender:sender];
}
-(void)save:(id)sender{
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSLog(#"selection is %#",selection);
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:selection forKey:#"preferenceName"];
[userData1 synchronize];
[self.navigationController pushViewController:note animated:YES];
}
viewcontroller1:
textView = [[UITextView alloc]initWithFrame:CGRectMake(0,0,320,400)];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:#"preferenceName"];
NSLog(#"saved is %#", savedValue);
textView.text = [NSString stringWithFormat:#"%#", savedValue];
Allocation of textView is in viewDidLoad.
Updating of textView is in viewWillAppear.
-(void) viewWillAppear:(BOOL)animated
[super viewWillAppear:animated];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:#"preferenceName"];
NSLog(#"saved is %#", savedValue);
textView.text = [NSString stringWithFormat:#"%#", savedValue];
}
I was checked your code just change NSSTring to NSString like below it will working.
-(void)save:(id)sender{
// NSSTring *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSString *selection = [wbCont stringByEvaluatingJavaScriptFromString:#"window.getSelection().toString()"];
NSLog(#"selection is %#",selection);
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:selection forKey:#"preferenceName"];
[userData1 synchronize];
[self.navigationController pushViewController:note animated:YES];
}
How can i pass an array value from a delegate class to view controller class
const char *query2=[tempQuery UTF8String];
NSMutableArray *arr1 = [[NSMutableArray alloc]init];;
if (sqlite3_prepare_v2(database,query2,-1,&statement1,NULL)==SQLITE_OK) {
//NSLog(#"vt", vt);
while (sqlite3_step(statement1)==SQLITE_ROW) {
vt=[[[Question1 alloc]init]autorelease];
vt.question=[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement1,3)];
[arr1 addObject:vt.question];
NSLog(#"arr1 is %#",[arr1 description]);
Where arr1 is an array value. So that array value has to pass in another class.
Thanks in advance.
In a class where you want to pass this "arr1" array do following steps:
1) define a array there (lets say it is aryTest)
2) make property for it
3) synthesize it
Now in a view where you are getting this "arr1" array.
From this view when ever you write code to push to next view do following steps:
NextViewController *objVc = [[NextViewController alloc] initWithNibName:#"NextViewController" bundle:nil];
objVc.aryTest = arr1;
[self.navigationController pushViewController:vc animated:YES];
[vc release];
so by this you will get this arr1 array into next view in aryTest array.
just create a Array method like in +(NSMutableArray *)getData in delegate class
+(NSMutableArray *)getData
{
const char *query2=[tempQuery UTF8String];
NSMutableArray *arr1 = [[NSMutableArray alloc]init];;
if (sqlite3_prepare_v2(database,query2,-1,&statement1,NULL)==SQLITE_OK) {
//NSLog(#"vt", vt);
while (sqlite3_step(statement1)==SQLITE_ROW) {
[arr1 addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement1,3)]];
NSLog(#"arr1 is %#",[arr1 description]);
}
}
return [arr1 autorelease];
}
in your view controller just call the method like
NSMutableArray * data=[[delegate getData]retain];
Try creating the array in your appDelegate. Thus it can be accessible in any view controller by calling your appDelegate:
myAppDelegate *myDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
arrayInView = [myDelegate msgFilter];
You can pass NSString or NSMutableArray using NSUserDefault method...
NSUserDefaultExample and Saving/Retrieving Data Using NSUserDefaults
For Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:#"TextToSave" forKey:#"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:#"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:#"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:#"floatKey"];
// saving an array
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
[prefs setObject:data forKey:#"lastResults"]
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
For Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:#"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:#"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:#"floatKey"];
// getting an array
NSData *dataRepresentingSavedArray = [prefs objectForKey:#"lastResults"];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
objectArray = [[NSMutableArray alloc] init];
}
or
filename *detailViewController = [[filename alloc] initWithNibName:#"filename" bundle:nil];
detailViewController.audio=#"yourData";
[self presentModalViewController:detailViewController animated:YES];
[detailViewController release];
Declare in filename.h
NSArray *audio;
#property(nonatomic,retain) NSArray *audio;
and filename.m
#synthesize audio;
thats all.
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 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];
}