Core data 如何使用swift 3.0更新核心数据中的多个记录

Core data 如何使用swift 3.0更新核心数据中的多个记录,core-data,swift3,nsurlsession,insert-update,Core Data,Swift3,Nsurlsession,Insert Update,我有一个json文件,我想通过它将json变量插入到核心数据中 -我已经解析了json -调用插入函数来保存数据 -调用fetch函数来显示数据 为了避免重复输入,我在解析之前应用了delete查询 但在功能上它是错误的,因为每次视图加载时,所有记录都会被解析和插入 所以我想应用更新查询,但不知道如何应用 下面是我的json文件 “数据”:[ { “NID”:9, “通知类型”:“一般”, “通知详情”:“所有学校的考试通知”, “通知”:“所有学校的考试通知”, }, { “NID”:

我有一个json文件,我想通过它将json变量插入到核心数据中 -我已经解析了json -调用插入函数来保存数据 -调用fetch函数来显示数据

  • 为了避免重复输入,我在解析之前应用了delete查询

    • 但在功能上它是错误的,因为每次视图加载时,所有记录都会被解析和插入

    • 所以我想应用更新查询,但不知道如何应用

下面是我的json文件

“数据”:[
{
“NID”:9,
“通知类型”:“一般”,
“通知详情”:“所有学校的考试通知”,
“通知”:“所有学校的考试通知”,
},
{
“NID”:6,
“通知类型”:“一般”,
“通知详情”:“通知所有学校tset目的”,
“通知”:“通知所有学校tset目的”,
},
{
“NID”:5,
“通知类型”:“一般”,
“通知详情”:“向所有学校进行测试”,
“通知”:“向所有学校进行测试”,
},
{
“NID”:4,
“通知类型”:“一般”,
“通知详情”:“所有测试的通知”,
“通知”:“所有测试的通知”,
},
{
“NID”:3,
“通知类型”:“一般”,
“通知详情”:“所有人的测试通知”,
“通知”:“所有人的测试通知”,
}
]

下面是我解析、插入和获取数据的代码

                    let responseJson = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String : AnyObject]


                    if let dataArray = responseJson?["Data"] as? NSArray
                    {
                        for i in 0..<(dataArray as AnyObject).count
                        {
                            let jsonObjectInLoop = dataArray[i] as! [String : Any]


                            let NIDObject = jsonObjectInLoop["NID"] as! Int32
                            print("Print NID Object from json loop \(NIDObject)")

                            let noticeType = jsonObjectInLoop["NoticeType"] as! String
                            let noticeDetail = jsonObjectInLoop["NoticeDetails"] as! String
                            let noticeTitle = jsonObjectInLoop["NoticeTitle"] as! String

                            let naFileNameString = ""

                                DatabseManager.sharedInstanceOfDatabase_Manager.insertNoticeFunc(nid_p: NIDObject , noticeType_p: noticeType , noticeDetails_p: noticeDetail , noticeTitle_p: noticeTitle)



                        }

                        self.fetchNotice()
                        DispatchQueue.main.async()
                        {
                                //code
                                self.DetailsTableView.reloadData()
                                self.refreshControl.endRefreshing()
                        }




                    }


                }
////

func insertNoticeFunc(nid_p: Int32, noticeType_p: String, noticeDetails_p: String, noticeTitle_p: String)
    {

        //Insert Data
        let contextVar = appDelegateShared.persistentContainer.viewContext
        let noticeDetailContext = NoticeDetails(context: contextVar)

        noticeDetailContext.nid = nid_p

        noticeDetailContext.noticeType = noticeType_p
        noticeDetailContext.noticeDetails = noticeDetails_p
        noticeDetailContext.noticeTitle = noticeTitle_p

        appDelegateShared.saveContext()

    }



/////

 func fetchNotice() -> Void
    {
        let contextVar = appDelegateShared.persistentContainer.viewContext

        //Fetch Data
        do
        {
            let fetchCoreData = try contextVar.fetch(NoticeDetails.fetchRequest())
            let noticeResult = fetchCoreData as! [NoticeDetails]

            print("notice result count \(noticeResult.count)")


            for notice in noticeResult
            {


                //Store Id's in NSUserDefault
                UserDefaults.standard.set(notice.nid, forKey: "nID_key")
                UserDefaults.standard.synchronize()

                print("NID from Core data \(notice.nid)")
                self.noticeIDArray.append(notice.nid)

                self.dateArray.append(notice.noticeDate!)
                self.noticeTitleArray.append(notice.noticeTitle!)
                self.imageUrlArray.append(notice.imageUrl!)
                self.noticeDescArray.append(notice.noticeDetails!)
                self.postedByArray.append(notice.postedBy!)

            }
            //print("Date Array : \(self.dateArray)")
        }
        catch
        {
            print("Error in fetch notice")
        }
    }
让responseJson=try?JSONSerialization.jsonObject(带:data!,选项:.allowFragments)为![字符串:AnyObject]
如果让dataArray=responseJson?[“数据”]as?不可变数组
{
因为我在虚空中
{
让contextVar=appDelegateShared.persistentContainer.viewContext
//获取数据
做
{
让fetchCoreData=尝试contextVar.fetch(NoticeDetails.fetchRequest())
让noticeResult=fetchCoreData为![NoticeDetails]
打印(“通知结果计数\(通知结果计数)”)
通知结果中的通知
{
//NSUserDefault中的存储Id
UserDefaults.standard.set(notice.nid,forKey:“nid_key”)
UserDefaults.standard.synchronize()
打印(“来自核心数据的NID\(notice.NID)”)
self.noticeIDArray.append(notice.nid)
self.dateArray.append(notice.noticeDate!)
self.noticeTitle数组.append(notice.noticeTitle!)
self.imageUrlArray.append(注意.imageUrl!)
self.noticedScarray.append(notice.noticedDetails!)
self.postedByArray.append(注意.postedBy!)
}
//打印(“日期数组:\(self.dateArray)”)
}
抓住
{
打印(“提取通知出错”)
}
}
我找了很多,但找不到合适的解决办法。
如果可能,请提供任何解决方案

如果您没有从后端接收到唯一的持久ID,那么唯一的方法是删除所有条目,然后插入新条目

在您的情况下,您可能会将
NID
作为唯一标识符。这意味着您可以从数据库中获取条目,或者在不存在条目的情况下创建一个新条目:

let noticeDetail: NoticeDetails = {
    if let existing = NoticeDetails.fetch(nid: myNID) {
        return existing
    } else {
        return NoticeDetails.createNewEntry()
    }
}()
... insert data to noticeDetail...
然后我假设一些可能被删除,所以您有两种情况。第一个服务器可能返回一个值
deleted:true/false
,如果它被删除,请尝试从数据库中获取并删除它

在您的情况下,您似乎没有这种优势,因此需要检查数组中缺少哪些。因此,除非您担心内存问题,否则最好先获取整个表,最后删除新响应中没有的条目:

var allDetails: [NoticeDetails] = NoticeDetails.findAll() // Get all details
// Iterate through parsed JSON response objects
myDetailDictionaries.forEach { item in 
   // Extract the unique identifier
   if let myNid = item[NID] as? String { 
      let noticeDetail: NoticeDetail = {
         if let (index, detail) = allDetails.enumerated.filtered { $0.nid == myNid }.first {
            allDetails.remove(at: index) // Remove the found object from the array
            return detail
         } else {
            return NoticeDetails.createNewEntry() // Create a new object
         }
      }()
   }
}
// Now allDetails consist only of objects that were not collected by the new response. So these need to be deleted.
allDetails.forEach { $0.deleteFromDatabase() }

或者,您可以查看核心数据的约束,该约束允许您定义哪些字段需要唯一,并将其设置为NID将合并条目,以便只存在唯一性。但这并不能解决删除问题,我也不会出于多种原因建议删除。如果您没有从后端接收唯一的持久性ID,则唯一的方法是删除所有条目,然后插入新条目

在您的情况下,您可能会将
NID
作为唯一标识符。这意味着您可以从数据库中获取条目,或者在不存在条目的情况下创建一个新条目:

let noticeDetail: NoticeDetails = {
    if let existing = NoticeDetails.fetch(nid: myNID) {
        return existing
    } else {
        return NoticeDetails.createNewEntry()
    }
}()
... insert data to noticeDetail...
然后我假设一些可能被删除,所以您有两种情况。第一个服务器可能返回一个值
deleted:true/false
,如果它被删除,请尝试从数据库中获取并删除它

在您的情况下,您似乎没有这种优势,因此需要检查数组中缺少哪些。因此,除非您担心内存问题,否则最好先获取整个表,最后删除新响应中没有的条目:

var allDetails: [NoticeDetails] = NoticeDetails.findAll() // Get all details
// Iterate through parsed JSON response objects
myDetailDictionaries.forEach { item in 
   // Extract the unique identifier
   if let myNid = item[NID] as? String { 
      let noticeDetail: NoticeDetail = {
         if let (index, detail) = allDetails.enumerated.filtered { $0.nid == myNid }.first {
            allDetails.remove(at: index) // Remove the found object from the array
            return detail
         } else {
            return NoticeDetails.createNewEntry() // Create a new object
         }
      }()
   }
}
// Now allDetails consist only of objects that were not collected by the new response. So these need to be deleted.
allDetails.forEach { $0.deleteFromDatabase() }
或者,您可以查看核心数据的约束,该约束允许您定义哪些字段需要唯一,并将其设置为NID将合并条目,以便只存在唯一性。但这并不能解决删除问题,我也不会出于多种原因建议删除