简体   繁体   中英

How to add bookmarkt to UITableView Cell & save to CoreData?

I have a question on adding bookmark/favorite button to a UITableView. Currently my mainVC has a tableView that is populated from a public database in CloudKit. If I want to add a bookmark/favorite button where the user can save the data for that row into CoreData (string objects, image, boolean type)...how I do I execute that?

I added the button as an outlet to UITableViewCell. In the cellForRow, I added

cell.favoriteButton.tag = indexPath.row

Then I added a @IBAction addFavorites to that MainVC, but I'm unsure how do I save all the objects to CoreData from that row?

This is my save to Core Data method:

if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext
{
   place = NSEntityDescription.insertNewObjectForEntityForName("Place", inManagedObjectContext: managedObjectContext) as! Place
   place.name = name!
   place.type = type!
   place.address = address!
   place.neighborhood = neighborhood!
   place.phoneNumber = phoneNumber!
   if let placeImage = imageView.image
   {
      place.image = UIImagePNGRepresentation(placeImage)
   }
   do {
      try managedObjectContext.save()
   } catch {
      print(error)
      return
   }

Any advice?

First, I think using tags is not a very good idea. To identify a row with a button use this method:

let point = button.convertPoint(CGPointZero, toView: tableView)
let indexPath = tableView.indexPathForRowAtPoint(point)!

Second, where are you getting your variables from? In your code it looks like you are using properties associated with the cell. That is also not a good idea because you should not use the view to read your data - instead use the original CloudKit data source.

Third, it is not advisable to store an image in Core Data unless it is just a small thumbnail. If it is larger, use external storage, devise a scheme in your application documents folder or download on demand from CloudKit.

Finally, it is not clear what else you need. I suppose you want to display the favorite status in the table view. If you could include some kind of unique identifier, you could check the existence of this identifier in cellForRowAtIndexPath in your Core Data set of objects and mark the cell accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM