Reputation: 53
I use UserDefualt to save array of Dictionary:
let pref = NSUserDefaults.standardUserDefaults();
var fav=pref.arrayForKey("favRecipes")!;
fav.append(self.dict);
pref.setObject(fav, forKey: "favRecipes");
before i save another data i check if it already exist:
@IBAction func addToFavorites(sender: UIButton) {
//not exist
if !isFavorite(){
var fav=pref.arrayForKey("favRecipes")!;
fav.append(self.dict);
pref.setObject(fav, forKey: "favRecipes");
print("added");
} //exist
else{
;
}
}
private func isFavorite()->Bool{
var fav=pref.arrayForKey("favRecipes")!;
for r in fav{
if r["id"]! as! Int==id{
return true;
}
}
return false;
}
The purpose of this code is to add something to your favorites list, and if its already there u have the option to remove it. for some reason i'm not succeeding to do the last part.
this my try so far:
func remove(event:UIAlertAction!){
var fav=pref.arrayForKey("favRecipes")!;
for r in fav{
if r["id"]! as! Int==id{
pref.removeObjectForKey("\(id)");
//pref.synchronize();
//fav=pref.arrayForKey("favRecipes")!;
//print(r["id"] as! Int);
}
}
}
ofcourse i tried to look and search about removing from dictionarys at userDefualt but nothing helps.
Upvotes: 1
Views: 626
Reputation: 57114
You have to change the array fav
and write that array back into the userDefaults. There is no object with the key \(id)
in the defaults, only an array for key favRecipes
which in turn contains an entry for the key id
.
func remove(event:UIAlertAction!){
var fav = pref.arrayForKey("favRecipes")!
fav = fav.filter { $0["id"] != id }
pref.setObject(fav, forKey: "favRecipes")
}
Upvotes: 1