更新或删除CoreData中的自定义对象

时间:2020-03-31 01:37:33

标签: swift core-data

我有一个使用CoreData的项目, 我创建自定义对象 Pic Of My Core Data Entity

这是我在属性

中使用的类
public class Item: NSObject, NSCoding {

public var name: String = ""
public var price: Int = 0
public var Quan: Int = 0

enum Key:String {
    case name = "name"
    case price = "price"
    case Quan = "Quan"
}

init(name: String, price: Int , Quan: Int) {
    self.name = name
    self.price = price
    self.Quan = Quan
}

public override init() {
    super.init()
}

public func encode(with aCoder: NSCoder) {

    aCoder.encode(name, forKey: Key.name.rawValue)
    aCoder.encode(price, forKey: Key.price.rawValue)
    aCoder.encode(Quan, forKey: Key.Quan.rawValue)
}

public required convenience init?(coder aDecoder: NSCoder) {

    let mName = aDecoder.decodeObject(forKey: Key.name.rawValue)
    let mPrice = aDecoder.decodeInt32(forKey: Key.price.rawValue)
    let mQuan = aDecoder.decodeInt32(forKey: Key.Quan.rawValue)

    self.init(name: mName as! String, price: Int(mPrice) , Quan: Int(mQuan) )
}
 }

这是我要保存并提取的代码

func Save()

    {
    let UserEntity = NSEntityDescription.entity(forEntityName: "OrdersHistory", in: context)
    let cmsg = NSManagedObject(entity: UserEntity!, insertInto: context) as! OrdersHistory

    var itemarray : [Item] = []

    for i in self.items
     {
     itemarray.append(Item(name: String(i.item!), price: Int(i.price), Quan: Int(i.quan)))
      }

    let data = [ "orderunique" : uniq , "receiptnumber" : result[0] , "date" : NSDate() as Date , "items" : itemarray] as [String : Any]
    cmsg.setValuesForKeys(data)

    do
    {

        ad.saveContext()

        print("Saved! ")
    }
    catch
    {
        print(error)
    }

    }

   func fetch()
   {
    var HistoryList = [OrdersHistory]()
   let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "OrdersHistory")
    do 
    {
     HistoryList = try context.fetch(fetchRequest) as! [OrdersHistory]
    } catch 
     {
     }

    }

直到现在一切都OK! , 但是当我想更新或删除[item]中的特定对象时, 我尝试了这种方法,但这是错误的,因为他只能删除 NSMangedObject

(无法将类型“ Item”的值转换为预期的参数类型“ NSManagedObject”) 见下文,我标记了错误所在

func delete()
  {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "OrdersHistory")

    fetchRequest.predicate = NSPredicate(format: "orderunique = %@", "\(orderdetail.orderunique!)")

     do 
    {
        let MainObject = try context.fetch(fetchRequest) as! [OrdersHistory]
        let ObjectToDelete = MainObject[0].items![0]
        context.delete(ObjectToDelete) //// Give me this error : Cannot convert value of type 'Item' to expected argument type 'NSManagedObject'
        }
    }

注意:如果我要删除项目中的所有项目或元素,则会显示该错误

有什么想法吗?

0 个答案:

没有答案