首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在swift 3中从核心数据中删除对象

如何在swift 3中从核心数据中删除对象
EN

Stack Overflow用户
提问于 2016-11-23 12:41:05
回答 1查看 6.8K关注 0票数 2

这就是我将数据保存到核心的方法,现在我想从整个数据中删除特定的对象。我该怎么做呢?

下面是我保存数据的方式:

代码语言:javascript
复制
func saveProductDetails(product : Product) {
        // set user_id 
        product.user_id = UserDefaults.sharedInstace.getCustomerId()
        //save data locally for the time been
        let entity = NSEntityDescription.entityForName("Product", inManagedObjectContext: self.writeContext)
        let category = NSEntityDescription.entityForName("Category", inManagedObjectContext: self.writeContext)
        let brand = NSEntityDescription.entityForName("Brand", inManagedObjectContext: self.writeContext)

        var entityProduct = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:self.writeContext)
        var entityCategory = NSManagedObject(entity: category!, insertIntoManagedObjectContext:self.writeContext)
        var entityBrand = NSManagedObject(entity: brand!,insertIntoManagedObjectContext: self.writeContext)

        entityProduct = product.settingManagedObject(entityProduct)
        entityProduct.setValue(String(Utill.sharedInstace.getTimeStamp()), forKey: "time_stamp")
        entityProduct.setValue(Constant.Status.STATUS_NOT_VERIFIED, forKey: "status")


        if product.categoryObject != nil{
            product.categoryObject.user_id = UserDefaults.sharedInstace.getCustomerId();
            entityCategory = product.categoryObject.settingManagedObject(entityCategory)
        }

        if product.brandObject != nil{
            product.brandObject.user_id = UserDefaults.sharedInstace.getCustomerId();
          entityBrand = product.brandObject.settingManagedObject(entityBrand)
        }

        entityProduct.setValue(entityCategory, forKey:"category")
        entityProduct.setValue(entityBrand, forKey: "brand")

        writeContext.performBlock {
            do {

                try self.writeContext.save()

                self.managedContext.performBlock({
                    do{
                        try self.managedContext.save()
                    } catch let error as NSError  {
                        print("Could not save \(error), \(error.userInfo)")
                    }

                })
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
                return
            }

        }

    }

这个Product对象与另外两个对象有关系,我只想删除特定的对象,而不是全部。这意味着在UITableView中删除( product.purchase_id == "selected_purchse_id")。

如何做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2016-11-23 13:22:06

检查此代码以执行swift 3核心数据操作

代码语言:javascript
复制
import CoreData

class CoreDataOperations: NSObject {

    // MARK: Save data
    func saveData() -> Void {
        let managedObjectContext = getContext()
        let personData = NSEntityDescription.insertNewObject(forEntityName: "Person", into: managedObjectContext) as! Person
        personData.name = "Raj"
        personData.city = "AnyXYZ"

        do {
            try managedObjectContext.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        } catch {

        }

    }

    // MARK: Fetching Data
    func fetchData() -> Void {

        let moc = getContext()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

        do {
            let fetchedPerson = try moc.fetch(fetchRequest) as! [Person]

            print(fetchedPerson.count)
            for object in fetchedPerson {
                print(object.name!)
            }

        } catch {
            fatalError("Failed to fetch employees: \(error)")
        }

    }



    // MARK: Delete Data Records

    func deleteRecords() -> Void {
        let moc = getContext()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

         let result = try? moc.fetch(fetchRequest)
            let resultData = result as! [Person]

            for object in resultData {
                moc.delete(object)
            }

            do {
                try moc.save()
                print("saved!")
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            } catch {

            }





    }

    // MARK: Update Data
    func updateRecords() -> Void {
        let moc = getContext()

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")

        let result = try? moc.fetch(fetchRequest)

            let resultData = result as! [Person]
            for object in resultData {
                object.name! = "\(object.name!) Joshi"
                print(object.name!)
            }
            do{
                try moc.save()
                print("saved")
            }catch let error as NSError {
                print("Could not save \(error), \(error.userInfo)")
            }


    }

    // MARK: Get Context

    func getContext () -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }
}

您可以从https://github.com/rajkumar24u/CoreDataOperations获得更多信息

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40756178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档