NSUserDefaults not getting stored string value - iphone

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];
}

Related

UITextView text not updating

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];

Just cannot figure out how to reloadData in UITableView using a navigationController

This is my first time asking a question & posting code so I hope I have included everything that is necessary.
In several of my other apps I have been able to successfully reloadData in a UITableView but for some reason I cannot get it to work here.
I am using a navigationController and drilling down a few levels in the UITableView until a new class loads which right now just has two buttons that switch between 2 similar plist files so I can tell that the tableView is actually reloading (Data.plist & Data2.plist)
This is eventually going to be a timesheet sort of app where individual jobs are listed and the user (driver) will punch a timeclock with In/Out buttons. For now, what I want is to drill down and click the button that loads the other plist and go back up to reveal that the new plist data has loaded. My problem is that I cannot get the tableView to reload at all. I've tried putting different variations of [self.tableView reloadData] & [myTableView reloadData] (which I have also connected via IB) all over the place but none of them work. I'm currently calling a method in the rootViewController (where the tableView is) from detailViewController (where the buttons are) and that basic process works for me in other apps when there is no navigationController being used. The navigationController seems to be throwing me off here in this app. I hope an easy solution can be found. My code so far looks like this:
AppDelegate.m
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
RootViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
//THIS ESTABLISHES WHICH PLIST TO LOAD BASED ON THE BUTTON CLICKED
plistToUse = [[NSUserDefaults standardUserDefaults] objectForKey:#"plistToUse"];
if (plistToUse == #"Data.plist") {
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Data.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
} else if (plistToUse == #"Data2.plist") {
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Data2.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
} else {
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Data.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
}
if(CurrentLevel == 0) {
NSArray *tempArray = [[NSArray alloc] init];
self.tableDataSource = tempArray;
[tempArray release];
self.tableDataSource = [self.data objectForKey:#"Rows"];
self.navigationItem.title = #"Choose Driver";
} else if (CurrentLevel == 1) {
self.navigationItem.title = #"Choose Day";
} else if (CurrentLevel == 2) {
self.navigationItem.title = #"Choose Job";
} else if (CurrentLevel == 3) {
self.navigationItem.title = #"Job Details";
} else {
self.navigationItem.title = CurrentTitle;
}
}
-(void)update {
dvController.labelHelper.text = #"UPDATED"; //USED TO SEE IF A LABEL IN THE BUTTON CLASS WILL UPDATE
NSArray *tempArray = [[NSArray alloc] init];
self.tableDataSource = tempArray;
[tempArray release];
self.tableDataSource = [self.data objectForKey:#"Rows"];
self.navigationController.navigationItem.title = #"Choose Driver";
self.navigationController.title = #"THE TITLE";
[myTableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
unsortedIndex=1;
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.tableDataSource count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
cell.textLabel.text = [dictionary objectForKey:#"Title"];
NSArray *Children = [dictionary objectForKey:#"Children"];
if ([Children count] == 0) {
Titles = [dictionary objectForKey:#"Title"];
in1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"InTime1"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", in1];
}
in1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"InTime1"];
out1 = [[NSUserDefaults standardUserDefaults] objectForKey:#"OutTime1"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#:%#", in1, out1];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
NSArray *Children = [dictionary objectForKey:#"Children"];
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:[NSBundle mainBundle]];
if([Children count] == 0) {
[self.navigationController pushViewController:dvController animated:YES];
dvController.labelSiteName.text = [dictionary objectForKey:#"Company"];
dvController.labelSiteAddress.text = [dictionary objectForKey:#"Address"];
dvController.labelSiteNotes.text = [dictionary objectForKey:#"Notes"];
[dvController.mapView setMapType:MKMapTypeStandard];
[dvController.mapView setZoomEnabled:YES];
[dvController.mapView setScrollEnabled:YES];
dvController.mapView.showsUserLocation = YES;
[dvController release];
}
else {
RootViewController *rvController = [[RootViewController alloc] initWithNibName:#"RootViewController" bundle:[NSBundle mainBundle]];
rvController.CurrentLevel += 1;
rvController.CurrentTitle = [dictionary objectForKey:#"Title"];
[self.navigationController pushViewController:rvController animated:YES];
rvController.tableDataSource = Children;
[rvController release];
}
}
DetailViewController.m
These are the two buttons that should reload the tableView with either Data.plist or Data2.plist
-(IBAction)getInTime1:(id)sender {
plistToUse = #"Data.plist";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:plistToUse forKey:#"plistToUse"];
[defaults synchronize];
[rvController update];
}
-(IBAction)getOutTime1:(id)sender {
plistToUse = #"Data2.plist";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:plistToUse forKey:#"plistToUse"];
[defaults synchronize];
[rvController update];
}
I appreciate any help you can give.
Add your data fetching from plist code into your viewDidAppear or viewWillAppear methods, so that each time view appears, the data is loaded from plist.
And also note that your arrays are allocated only once.
This will work for you.

How to pass array value from one class to other class

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.

NSUserDefaults doubts in iphone SDK

I am integrating twitter in my app for sharing a text. My architecture of twitter integration is I have two Button _btnTwitter and _btntwitteLogout and when the user successfully login the twitter his name will display in _btntwitterLogout as title.
When the user tap the _btntwitterLogout it logs out the twitter and logout button hides and login button comes.every thing went ok.but when the user tap the login button(_btnTwitter) the Twitter login popup cmes for login purpose,here is the problem that am facing ,when the popup comes the user tap the cancel button of that popup the popup disappears and here the previous username of the user in the logout button.it didn't changes. I have put user defaults to check.
-(IBAction)_clickbtnTwitter:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Twitter_logged"];
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btntwitterLogeout.hidden = NO;
_btnTwitter.hidden=YES;
if (_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else {
[_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. %#", [NSDate date]]];
}
}
}
then logout code
-(IBAction)_clickbtntwitterlogeout:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"Twitter_logged"];
crosstwitterimage.hidden = YES;
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btntwitterLogeout.hidden = YES;
_btnTwitter.hidden=NO;
_btnTwittermain.enabled = NO;
[_engine clearAccessToken];
[_engine clearsCookies];
[_engine setClearsCookies:YES];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"authData"];
[[NSUserDefaults standardUserDefaults]removeObjectForKey:#"authName"];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"authName"]);
NSLog(#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"authData"]);
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"Twitter_logged"];
[_engine release];
_engine=nil;
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"twitter"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
}
in viewwillappear
BOOL logged = [[NSUserDefaults standardUserDefaults] boolForKey:#"Twitter_logged"];
;
if (logged == YES) {
_btnTwitter. hidden = YES;
_btntwitterLogeout.hidden = NO;
crosstwitterimage.hidden = NO;
_btnTwittermain.enabled =YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Checks if there is a saved User Name
if([defaults objectForKey:#"kTwitterUserName"])
{
NSString *username = [defaults objectForKey:#"kTwitterUserName"];
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
crosstwitterimage.hidden = NO;
}
}
else
{
_btnTwitter. hidden = NO;
crosstwitterimage.hidden = YES;
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btnTwittermain.enabled =NO;
crosstwitterimage.hidden = YES;
}
but when i tap the cancel button in loginwindow of twitter,an comes back the username with the logout button shows ,if the user is already logedout from twitter.
is there any problem in my code.
thanks in advance.
EDIT
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
#pragma mark SA_OAuthTwitterControllerDelegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults synchronize];
}
- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Failed!");
}
- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Canceled.");
}
#pragma mark TwitterEngineDelegate
- (void) requestSucceeded: (NSString *) requestIdentifier {
NSLog(#"Request %# succeeded", requestIdentifier);
}
- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {
NSLog(#"Request %# failed with error: %#", requestIdentifier, error);
}
Yes there is a problem. Whenever you hit the _btnTwitter, you are setting the Twitter_logged to yes. That's not correct. You should only set it to yes when there is a successful login. That is when the user has NOT hit cancel on the twitter login window.
In other words, you need to set the Twitter_logged to YES once the user has actually logged in, not when the user clicked on the button _btnTwitter
Seems like SA_OAuthTwitterController has a delegate property pointing to self. You should handle code to set Twitter_logged YES in that delegate method.
Hope that helps.
Edit:
Given the latest code here is where you should add the NsUserDefaults data
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults setBool:YES forKey:#"Twitter_logged"]; // Right here - mbh
[defaults synchronize];
}

Fail to addObject to NSMutableArray

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);
}