在swift

时间:2018-03-28 01:52:01

标签: ios swift core-data

我需要一些帮助在swift中创建一个喜欢的按钮。我一直在努力研究如何使用核心数据,我认为我对它有一个很好的处理,我希望我很难用它来创建最喜欢的按钮。我有一个示例项目有两个视图,一个带有几个数字的表视图和一个带有按钮的视图控制器。 this is what it should look like

这是应用程序的核心数据部分 core data

观看视频后,我被告知采取从appDelegate保存数据的核心数据函数并将其放入新视图中,我称之为PersistenceService.swift

import Foundation
import CoreData

class PersistenceService {

    private init() {}

    static var context: NSManagedObjectContext {
        return persistentContainer.viewContext
    }

    static  var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "otherButton")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    static func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
                print("SAVED")
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

第一个视图,tableview,很简单,我刚刚创建了一个包含三个单元格的表格,按下时会转到新视图。

idTableView.swift

import UIKit
import CoreData

class idTableView: UITableViewController {


    var idNumber = [1, 2, 3]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "segue", sender: indexPath)
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return idNumber.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! idCell
        cell.idCell.text = "\(idNumber[indexPath.row])"
        return cell
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segue" {
            let nxtVC = segue.destination as? ViewController
            let myIndexPath = self.tableView.indexPathForSelectedRow!
            let row = myIndexPath.row
            nxtVC?.idNumber = idNumber[row]
        }
    }

当按下来自idTableView.swift的单元格时,它会转到一个新视图,中间有一个空星形按钮。

ViewController.swift

import UIKit
import CoreData

class ViewController: UIViewController {

    var buttonIsSelected = false

    @IBOutlet var navigation: UINavigationItem!
    var idNumber: Int?

    @IBOutlet var onOffButton: UIButton!
    let image1 = UIImage(named: "empty") as UIImage?
    let image2 = UIImage(named: "filled") as UIImage?

    override func viewDidLoad() {
        super.viewDidLoad()
        getId()

    }
//button Action
    @IBAction func onOffButtonPressed(_ sender: Any) {
        buttonIsSelected = !buttonIsSelected
        if buttonIsSelected == true {
            getFavorite(bool: buttonIsSelected)
            print("favorited")
            onOffButton.setImage(image2, for: .normal)
        } else if buttonIsSelected == false {
            getFavorite(bool: buttonIsSelected)
            print("unfavorited")
            onOffButton.setImage(image1, for: .normal)
        }
    }
    func getId() {
        if let id = idNumber {
            let newNumber = NSEntityDescription.insertNewObject(forEntityName: "IdNumber", into: PersistenceService.context) as! IdNumber
            let newBool = NSEntityDescription.insertNewObject(forEntityName: "Favorite", into: PersistenceService.context) as! Favorite
            newNumber.setValue(Int16(id), forKey: "idNumber")
            newBool.setValue(buttonIsSelected, forKey: "favorite")
            newNumber.favorite = newBool
            print("newNumber: \(newNumber.favorite)")
            print("newBool: \(newBool)")
            PersistenceService.saveContext()
            //self.navigationItem.title = "\(id)"
        }
    }

    func getFavorite(bool: Bool) {
        let newFavorite = NSEntityDescription.insertNewObject(forEntityName: "Favorite", into: PersistenceService.context)
        newFavorite.setValue(bool, forKey: "favorite")
        PersistenceService.saveContext()
    }

我所看到的核心数据就像创建一个工作场所应用程序,其中有部门是父部门,然后是填充部门的人员。这些应用程序创建了一个部门,然后将人员添加到该部门,然后填充tableView。 我想要做的是不同的,因为我的父母在这种情况下是身份证号码,每个身份证号码只有一个布尔。当bool改变时,它会将按钮的图像更改为填充的星形。我无法做的是将每个bool保存到每个id号。例如,我有三个id号,这三个id号中的每一个都可以有一个bool,如1:true,2:false。 3:是的。每个id号的默认值为false,但是当按下该按钮时,它应该保存bool的更改,这反过来会改变按钮的图像。

我认为我遇到的问题是在代码中获得正确的关系。似乎我可以为单个视图执行此操作,但是当我转到不同的视图时,应用程序崩溃或其他东西,但是我更改为默认状态之前保存的按钮状态,这是假/空星按钮。

如果有人有问题,我会尽我所能回答。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

我会以不同的方式设计: 出于您的目的,您只需要一个CD对象,其具有属性idNumber和Bool isFavorite。当您加载tableView时,您将从CD获取所有相关对象并将其保存在idNumber数组中。然后,您可以轻松访问所选TableView单元格的数组元素,只需设置isFavorite,然后保存您的CD上下文。

如果您希望使用isFavorite == true获取所有对象,则可以使用具有此谓词的请求执行提取...

每当getID被称为新对象时,您的创建方式是什么?一旦创建,你想要重用它当然...否则你将有多个具有相同idNumber的对象...

顺便说一下:完全没必要自己为CD对象创建ID。默认情况下,所有CD对象都具有唯一的ID。在CD中,你只需要关心你的自然属性和关系。

答案 1 :(得分:0)

从故事板中为所选和默认按钮设置InvalidClassExceptions图像。

enter image description here enter image description here

然后选择并取消选择以编程方式管理。

UIbuton