使用CoreData的收藏夹按钮

时间:2019-05-10 17:47:20

标签: swift database button entity favorites

我只需要向数据库添加一个条目。如果数据库为空,则由于某种原因不添加任何内容。如果数据库中有记录,则由于周期原因,我添加了几个相同的记录。这是我的代码:

import UIKit
import AVFoundation
import CoreData

class PlayerViewController: UIViewController, VLCMediaPlayerDelegate {
@IBOutlet var favoriteBarButton: UIBarButtonItem!

@IBAction func addFavorites(_ sender: UIBarButtonItem) { 
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "MarkersModel", in: context)

let request: NSFetchRequest<MarkersModel> = MarkersModel.fetchRequest()
request.returnsObjectsAsFaults = false
request.includesPropertyValues = false
    do {                    let result = try context.fetch(request)

                                            for (i, s) in result.enumerated() {
                                                // Can simply use 'sender' here, no need to index into senderArray.
                                                if s.nameCam == self.webcamTitle! {
                                                    let value = result[i]
                                                    context.delete(value)
                                                    self.favoriteBarButton?.tintColor = .red
                                                    //do {
                                                    try context.save()
                                                    //}
                                                }
                                                if s.nameCam != self.webcamTitle!
                                                {
                                                    let newFavoriteCamera = NSManagedObject(entity: entity!, insertInto: context)
                                                    newFavoriteCamera.setValue(self.webcamTitle, forKey: "nameCam")
                                                    newFavoriteCamera.setValue(self.webcamURL, forKey: "urlCam")
                                                    self.favoriteBarButton?.tintColor = .green
                                                    //do {

                                                    //let value = result[i]
                                                    context.insert(newFavoriteCamera)
                                                    try context.save()
                                                    //}
                                                }
                                            }
}

enter image description here

2 个答案:

答案 0 :(得分:0)

加载:

var DataItem = [EntityName]()

if (DataItem.value(forKeyPath: "favorite") as? Bool)! == true {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_selected"), for: .normal)
} else {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_unselected"), for: .normal)
}

按钮操作:

if FavoriteButton.currentImage == UIImage(named: "Star_white_selected") {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_unselected"), for: .normal)
   updateData(add: false)
} else if FavoriteButton.currentImage == UIImage(named: "Star_white_unselected") {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_selected"), for: .normal)
   updateData(add: true)
}

func updateData(add: Bool) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Name")
    fetchRequest.predicate = NSPredicate(format: "nameCam = %@", self.webcamTitle)

    do {
        let test = try managedContext.fetch(fetchRequest)
        let objectUpdate = test[0]
        objectUpdate.setValue(add, forKey: "favorite")
        appDelegate.saveContext()
    } catch {
        print(error)
    }
}

答案 1 :(得分:0)

我做了我想做的。这是我对任何有兴趣的代码。有效=)

@IBAction func addFavorites(_ sender: UIBarButtonItem) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "MarkersModel", in: context)
    let request: NSFetchRequest<MarkersModel> = MarkersModel.fetchRequest()
    request.returnsObjectsAsFaults = false
    var array: [String] = []

    do {
        let result = try context.fetch(request)
        for data in result {
            array.append(data.nameCam!)
            print(array)
        }
    }catch {
        print(error)}
    do {
        let newFavoriteCamera = NSManagedObject(entity: entity!, insertInto: context)
        newFavoriteCamera.setValue(self.webcamTitle, forKey: "nameCam")
        newFavoriteCamera.setValue(self.webcamURL, forKey: "urlCam")
        let result = try context.fetch(request)

        if array.contains(self.webcamTitle) {
            for data in result {
                if data.nameCam == self.webcamTitle {
                    favoriteBarButton?.tintColor = .red
                    print("YES")
                    context.delete(data)
                    try context.save()
                }
            }
        } else{
            print("NO")
            self.favoriteBarButton?.tintColor = .green
            try context.save()
            print(array)
        }
    } catch {
        print(error)}
}


func RequestFromDB() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "MarkersModel", in: context)

    let request: NSFetchRequest<MarkersModel> = MarkersModel.fetchRequest()
    request.returnsObjectsAsFaults = false

    var array1: [String] = []

    do {
        let result = try context.fetch(request)
        for data in result {
            array1.append(data.nameCam!)
        }
    } catch {
        print(error)}

    print(array1)
    //let u = "Maine, Caribouw"
    if array1.contains(self.webcamTitle) {
        print("YES")
        self.favoriteBarButton?.tintColor = .green
    } else{
        print("NO")
        self.favoriteBarButton?.tintColor = .red
    }


}
override func viewDidLoad() {
    super.viewDidLoad()
    RequestFromDB()

}