Remove object of NSUserDefault by tableview cell

牧云@^-^@ 提交于 2019-12-13 05:30:24

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/9646403/remove-object-of-nsuserdefault-by-tableview-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!