Add cell to favorites tableview with core data

邮差的信 提交于 2019-12-03 23:05:44

If a list of favourites as Strings is all you need to persist in your app, you might be able to simply use NSUserDefaults instead of Core Data.

To save an array of favorites:

let favorite = UITableViewRowAction(style: .Normal, title: "Favorite") { (action, indexPath) in
    var favorites : [String] = []
    let defaults = NSUserDefaults.standardUserDefaults()
    if let favoritesDefaults : AnyObject? = defaults.objectForKey("favorites") {
        favorites = favoritesDefaults! as [String]
    }

    favorites.append(tableView.cellForRowAtIndexPath(indexPath).textLabel!.text)
    defaults.setObject(favorites, forKey: "favorites")
    defaults.synchronize()
}

To read the array of favorites in your favorites page:

var favorites : [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    let defaults = NSUserDefaults.standardUserDefaults()
    if let favoritesDefaults : AnyObject? = defaults.objectForKey("favorites") {
        favorites = favoritesDefaults! as [String]
    }

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