gpt4 book ai didi

ios - 在 swift 中创建收藏按钮的核心数据关系

转载 作者:行者123 更新时间:2023-11-28 07:51:30 25 4
gpt4 key购买 nike

我需要一些帮助来快速创建收藏夹按钮。我一直在努力研究如何使用核心数据,我认为我已经很好地掌握了它,期望我很难用它来创建收藏夹按钮。我有一个示例项目,它有两个 View ,一个有几个数字的 TableView 和一个有按钮的 View Controller 。 this is what it should look like

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

看完视频后,我被告知要获取从 appDelegate 保存数据的核心数据函数,并将其放在一个新 View 中,我称之为 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)")
}
}
}
}

第一个 View ,tableview,很简单,我只是创建了一个包含三个单元格的表格,当按下这些单元格时会转到一个新 View 。

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 中的单元格时,它会将您带到一个新 View ,中间有一个空的星形按钮。

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。我想做的是不同的,因为在这种情况下我的 parent 是身份证号码,每个身份证号码只有一个 bool 值。更改 bool 时,它会将按钮的图像更改为实心星形。我遇到的麻烦是将每个 bool 值保存到每个 ID 号。例如,我有三个 ID 号,这三个 ID 号中的每一个都可以有一个 bool 值,例如 1:true,2:false。 3:真实。每个 id 号的默认值都是 false,但是当按下按钮时,它应该保存 bool 的变化,这反过来又改变了按钮的图像。

我认为我遇到的问题是在代码中建立正确的关系。似乎我可以为单个 View 执行此操作,但是当我转到另一个 View 时,应用程序崩溃或其他原因,但我在更改为默认状态之前保存的按钮状态是错误/空星按钮。

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

最佳答案

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

如果你想获取所有带有 isFavorite == true 的对象,你可以简单地使用具有谓词的 Request 执行提取...

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

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

关于ios - 在 swift 中创建收藏按钮的核心数据关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49524865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com