Swift 核心数据更改 bool 存储
Posted
技术标签:
【中文标题】Swift 核心数据更改 bool 存储【英文标题】:Swift core data change bool stored 【发布时间】:2020-06-19 16:02:26 【问题描述】:我正在为列表制作和扩展一个应用程序,并在执行过程中添加额外的数据。我添加了一个布尔值来将项目标记为已完成。
我想更改存储在核心数据中的布尔值。我可以添加和删除订单,但现在我正在寻找更改属性。请问我可以帮助我改变这些的最佳方式吗?
我已完成功能更改,但不知道如何让它在我的核心数据管理器中工作。
class CoreDataManager
static let shared = CoreDataManager(moc: NSManagedObjectContext.current)
var moc: NSManagedObjectContext
private init(moc: NSManagedObjectContext)
self.moc = moc
private func fetchOrder(name: String) -> Order?
var orders = [Order]()
let request: NSFetchRequest<Order> = Order.fetchRequest()
request.predicate = NSPredicate(format: "name == %@", name)
do
orders = try self.moc.fetch(request)
catch let error as NSError
print(error)
return orders.first
func changeCompleated(name:String, completed: Bool)
do
if let order = fetchOrder(name: name)
self.moc.perform
try self.moc.save()
catch let error as NSError
print(error)
func deleteOrder(name: String)
do
if let order = fetchOrder(name: name)
self.moc.delete(order)
try self.moc.save()
catch let error as NSError
print(error)
func getAllOrders() -> [Order]
var orders = [Order]()
let orderRequest: NSFetchRequest<Order> = Order.fetchRequest()
do
orders = try self.moc.fetch(orderRequest)
catch let error as NSError
print(error)
return orders
func saveOrder(id: UUID, name: String, type: String, qty: Double, urgent: Bool, complete: Bool)
let order = Order(context: self.moc)
order.id = id
order.name = name
order.type = type
order.qty = qty
order.urgent = urgent
order.complete = complete
do
try self.moc.save()
catch let error as NSError
print(error)
【问题讨论】:
【参考方案1】:差不多,只要加一行改变值,perform
块就不需要了
func changeCompleated(name: String, completed: Bool)
guard let order = fetchOrder(name: name) else return
do
order.complete = completed
try self.moc.save()
catch
print(error)
你也可以缩短fetchOrder
private func fetchOrder(name: String) -> Order?
let request: NSFetchRequest<Order> = Order.fetchRequest()
request.predicate = NSPredicate(format: "name == %@", name)
do
return try self.moc.fetch(request).first
catch
print(error)
【讨论】:
以上是关于Swift 核心数据更改 bool 存储的主要内容,如果未能解决你的问题,请参考以下文章