I have a list of favorites that are stored in the NSUserDefaults, single favorited are stored by NSDictionary:
NSUserDefaults *userPref = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:author.text forKey:#"author"];
[bookmark setValue:book.text forKey:#"book"];
[bookmarks addObject:bookmark];
[userPref setObject:bookmarks forKey:#"bookmarks"];
[userPref synchronize];
Everything is ok, but now I want to delete a single favorite with the swipe of a cell. I have add the method for show the the delete swipe but I do not know how to remove the single bookmark from nsuserdefaults.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
[self.listBookamrks removeObjectAtIndex:row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
}
NSUserDefaults *userPref = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *storedBookMark = [[userPref ObjectForKey:#"bookmarks"]mutable copy];
// If you want to remove an object from the dictionary
[storedBookMark removeObjectForKey:#"Your KEy"];
// if you want to empty the dictionary
[storedBookMark removeAllObjects];
[userPref setObject: storedBookMark forKey:#"bookmarks"];
[userPref synchronize];
// if you want to store nil // go back to default state ..
[userPref setNilValueForKey:#"bookmarks];
Related
I am trying to save data via NSUserDefaults and view it on the tableView but nothing happen after I click on the save button, after I stop and run the application again the data that I saved it I can see it which every time it overwrite on the old data. Am I doing something wrong? Or should I use something different from NSUserDefaults?
Thanks in advance.
-(IBAction)save{
NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults];
[add1 setObject:txt1.text forKey:#"txt1"];
[add1 synchronize];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
self.dataArray = [NSArray arrayWithObjects:[prefs objectForKey:#"txt1"], nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [dataArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text=string;
return cell;
}
There are two issues in your code:
You are not refreshing the tableview. You can do this by calling:
[self.tableView reloadData]; // Or whatever property is pointing to your tableview
Every time you save a value, you save it under the same key (txt1) and that's why you override every time. If you want a list of items (an array) and to append the item into this array, you could do something like this:
NSMutableArray *myList = [[[NSUserDefaults standardUserDefaults] valueForKey:#"myTxtList"] mutableCopy];
[myList addObject:txt1.text];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithArray:myList] forKey:#"myTxtList"];
[add1 synchronize];
self.dataArray = myList;
[self.tableView reloadData];
P.S. Of course you need to set your dataArray accordingly in your viewDidLoad:
self.dataArray = [[NSUserDefaults standardUserDefaults] objectForKey:#"myTxtList"];
As A for Alpha said try that & in addition I am having doubt in your save method definition too. Just try changing it to the following
-(IBAction)save:(id)sender{
NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults];
[add1 setObject:txt1.text forKey:#"txt1"];
[add1 synchronize];
[tableView reloadData];
}
This may work out for u.
I guess you need to call [yourTableView reloadData] after saving the data in userDefaults. This should solve your problem.
Here is my code to delete value. Table view is deleting record temporary when I restart my app it will show deleted records also...
-(void)tableView:(UITableView *)atableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[bookmarks removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
[[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:#"Bookmarks"]; [self.tableView reloadData];
}
}
Please Help.
Try this :
// Your code
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:bookmarks forKey:#"Bookmarks"];
// saving it all
[prefs synchronize];
EDIT: I got a saving and now It do not work.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:countries forKey:#"country"];
[defaults synchronize];
Saving.
But I think I must load the arrays from the appsettings. how?
Got this now:
countries = [[NSArray alloc] initWithObjects:#"All",#"Austria",#"Belarus",#"Canada",#"Czech Republic",#"Denmark",#"Germany",#"Finland",#"France",#"Latvia",#"Norway",#"Russia",#"Slovakia",#"Slovenia",#"Switzerland",#"Sweden", #"USA", nil];
Use synchronize mathod of NSUserDefault.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int newRow = [indexPath row];
int oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;
if (newRow != oldRow)
{
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:
indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:
lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;
lastIndexPath = indexPath;
}
NSUInteger row = [indexPath row];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Suppose you have used **myArrayUsedInTableView** Array to construct TableView
..................................................................................
............./*Do changes here in myArrayUsedInTableView as per your requirement*/
....................................................................................
//Now store your array myArrayUsedInTableView in NSUserDefault
[defaults setObject:myArrayUsedInTableView forKey:#"StoredArray"];
[defaults synchronize];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
hi
i am trying to save state of ticked row in nsuserdefaults.Some how i am getting error
:setObject undeclared.
my code is as:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
NSInteger newRow = [indexPath row];
NSInteger oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;
if(newRow != oldRow)
{
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;
lastIndexPath = indexPath;
}
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
prefs = [setObject:lastIndexPath forKey:#"lastIndexPath"];
}
also i am trying to fetch row state in viewdidload method(should i fetch here?in view did load).my code is as:
- (void)viewDidLoad {
menuList=[[NSMutableArray alloc] initWithObjects:
[NSArray arrayWithObjects:#"LOCATION1",nil],
[NSArray arrayWithObjects:#"LOCATION2",nil],
[NSArray arrayWithObjects:#"LOCATION3",nil],
[NSArray arrayWithObjects:#"LOCATION4",nil],
[NSArray arrayWithObjects:#"LOCATION5",nil],
[NSArray arrayWithObjects:#"LOCATION6",nil],
[NSArray arrayWithObjects:#"LOCATION7",nil],
nil];
[self.navigationController setNavigationBarHidden:NO];
self.navigationController.navigationBar.tintColor=[UIColor blackColor];
self.navigationController.navigationBar.barStyle=UIBarStyleBlackTranslucent;
self.title=#"Location Selection";
[table reloadData];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:#"lastIndexPath"] compare: indexPath]== NSOrderedSame){
cell.AccessoryType = UITableViewCellAccessoryCheckMark;
}
[super viewDidLoad];
}
and getting errors: indexPath Undeclared and cell undeclared.
i am getting why these errors are coming coz both of them(indexpath and cell) are not in scope,then where to place this code(nsuserdefaults data retriving code).Please guide my.
Thanks!
Try replacing this:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
prefs = [setObject:lastIndexPath forKey:#"lastIndexPath"];
With this:
[[NSUserDefaults standardUserDefaults] setObject:lastIndexPath forKey:#"lastIndexPath"];
Your error is because you are invoking setObject:forKey: without specifying that your prefs object is calling it. So the compilor is not identifying it as a valid message. You are also trying to assing that messages output to your prefs object, which is not correct.
This said, I am pretty sure you cant store an NSIndexPath inside of a plist directly, you would either have to store as an NSNumber, NSString, or NSData.
This would look like this:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:lastIndexPath.row] forKey:#"lastIndexPath"];
My app downloading posts from internet to UITableViewCell. When user taps on cell, i am need to set this article as read (like on Mail.app). I dont know how to do that.
I am adding url (when user press cell) to database (like "url|url|url"), open detail view. And when he goes back to UITableView checking existing url in DB. Table now is too slow!
Can u help me and say what other method i can use to do that? Like in mail.app. I am using custom cell and code in drawRect method. Please, help
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",indexPath.row];
NSMutableArray *array=[NSMutableArray array];
if([[NSUserDefaults standardUserDefaults] objectForKey:#"readPostS"]!=nil)
[array addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"readPostS"]];
NSUInteger indexOfObject = [array count]>0?[array indexOfObject:[NSNumber numberWithInt:indexPath.row]]:100000; //I add this, because row don't want update using updateRowAtIndexPath
QuickCell *cell = (QuickCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil || (indexOfObject!=NSNotFound && indexOfObject!=100000))
{
cell = [[[QuickCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.frame = CGRectMake(0.0, 0.0, 320.0, 68.0);
cell.accessoryType = UITableViewCellAccessoryNone;
if([self.subject count]>0)
{
[self.allImages addObject:[NSNull null]];
NSString *userNameLJ = [NSString stringWithFormat:#"%#",[self.journalurl objectAtIndex:indexPath.row]];
userNameLJ = [userNameLJ stringByReplacingOccurrencesOfString:#"http://"
withString:#""];
userNameLJ = [userNameLJ stringByReplacingOccurrencesOfString:#".livejournal.com"
withString:#""];
userNameLJ = [userNameLJ stringByReplacingOccurrencesOfString:#"community/"
withString:#""];
NSString *postURL = [NSString stringWithFormat:#"http://m.livejournal.com/read/user/%#/%#",userNameLJ,[self.ditemid objectAtIndex:indexPath.row]];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[self.subject objectAtIndex:indexPath.row] forKey:#"title"];
[dict setObject:[Utilities replaceForCell:[Utilities flattenHTML:[self.entry objectAtIndex:indexPath.row]]] forKey:#"description"];
if([[database executeQuery:#"SELECT * FROM read WHERE posts=?;",postURL] count]>0)
{
//if this post is read
[dict setObject:[NSNumber numberWithBool:NO] forKey:#"highlighted"];
}
else {
[dict setObject:[NSNumber numberWithBool:YES] forKey:#"highlighted"];
}
[dict setObject:[self.journalname objectAtIndex:indexPath.row] forKey:#"nick"];
[cell setContentForCell:dict];
BOOL trueOrFalse = [[self.allImages objectAtIndex:indexPath.row] isKindOfClass:[NSNull class]]?YES:NO;
if(trueOrFalse)
{
if (tableView.dragging == NO && tableView.decelerating == NO)
{
//if no image cached now, download it
if(indexPath.row<6 && self.updating==YES)
[self startDownloading:indexPath];
if(self.updating==NO)
[self startDownloading:indexPath];
}
}
else
{
[cell setImageForCell:[self.allImages objectAtIndex:indexPath.row]];
}
}
if(indexOfObject!=NSNotFound && indexOfObject!=100000)
{
//delete this row from userdefaults
[array removeObjectAtIndex:indexOfObject];
if([array count]>0)
[[NSUserDefaults standardUserDefaults] setObject:array forKey:#"readPostS"];
else [[NSUserDefaults standardUserDefaults] removeObjectForKey:#"readPostS"];
}
}
return cell;
}
//////////////////////////////////////////////////////////////
///////-(void)viewWillApear
//////////////////////////////////////////////////////////////
NSMutableArray *readPosts = [NSMutableArray array];
if([[NSUserDefaults standardUserDefaults] objectForKey:#"readPostS"]!=nil)
{
[readPosts addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"readPostS"]];
self.read = (NSMutableArray*)[database executeQuery:#"SELECT * FROM read;"];
for(int i=0;i<[readPosts count];i++)
{
[self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[[readPosts objectAtIndex:i] intValue] inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
}
///////////////////////////////////////////////
///////THIS FILE OPENS POSTS FOR READING
///////////////////////////////////////////////
if([[database executeQuery:#"SELECT * FROM read WHERE posts=?;",self.postURL] count]==0)
{
[database executeNonQuery:#"INSERT INTO read VALUES (?);",self.postURL];
NSMutableArray *defaults = [NSMutableArray array];
if([[NSUserDefaults standardUserDefaults] objectForKey:#"readPostS"]!=nil)
defaults = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"readPostS"]];
[defaults addObject:[NSNumber numberWithInt:self.currentIndex]];
[[NSUserDefaults standardUserDefaults] setObject:defaults forKey:#"readPostS"];
}
Ok. I think, my code is to bad and u can understand, what i am doing here) Answer on other question. How i can update hidden cells? User see only 6 cell in a moment, i need to update, for example, 10 cells. How?
Or, how reload cell, if it allready exists? Lets say -
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",indexPath.row];
QuickCell *cell = (QuickCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[QuickCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.frame = CGRectMake(0.0, 0.0, 320.0, 68.0);
cell.accessoryType = UITableViewCellAccessoryNone;
.........}
now cell exists and if i call reload data nothing happen. And reloadCellAtIndexPath does not working too, because cell has unique identifier and ixists.
HOW I CAN RELOAD CELL AND CALL DRAWRECT AGAIN?))
You can implement this functionality by adding your code in the
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//Add the indexPath.row values in an array.
}
Add the custom functionality (like showing Title in BOLD for unread) in the
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Check if the indexPath.row is available in the array
//If yes then Normalize the fonts
//Else Keep them BOLD.
}
Unless you're really doing some drawing, don't implement in drawRect:. I don't know you're specific code, so that may not be correct in your case.
To reload the entire table (all cells), look at UITableView's - (void)reloadData
To reload a specific cell, look at UITableView's - (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation and use it to reload the cell in question.