Remove object of NSUserDefault by tableview cell

2019-09-02 11:20发布

问题:

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