从Core Data获取时出现问题

时间:2017-09-25 11:48:50

标签: ios database xcode core-data swift3

我在swift中第一次遇到这个非常奇怪的问题。我在json中有8个值。通过服务我正在解析json并在coreData中保存这些值。所有8个值都被保存。但是当我从该表中获取值时。它有时返回4个值或5或3个,如随机但不是全部。我甚至没有应用任何谓词。因为我无法理解这个问题所以我很难受。

这就是我在CoreData中保存它的方式:

    for field in json as? [AnyObject] ?? [] {

     self.SaveDayViewDetails(monthlyid: (field["MonthlyID"] as! String), mioauthid: (field["MIOAuthID"] as! String), empid: (field["EmpID"] as! String), doctorid: (field["DoctorID"] as! String))

  }

class func SaveDayViewDetails (monthlyid: String, mioauthid: String, empid : String,doctorid : String,doccode : String,callplanneractivityid : String,actid : String,startdate : String,speciality : String,s3 : String,s2 : String,s1 : String,plannerid : String,p4 : String,p3 : String,p2 : String,p1 : String,mstatus : String,miostatusreason : String,miostatus : String,miodescription : String,isexecuted : String,g1 : String,end_date : String,doctorname : String,classname : String,address : String,actname : String,actfcolor : String,actbcolor : String,editable : String,planmonth : String,date:String) {
        let context = getContext()

        let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        privateMOC.parent = context
        //retrieve the entity that we just created
        let entity =  NSEntityDescription.entity(forEntityName: "Tbl_SchedularDayView", in: context)
        let transc = NSManagedObject(entity: entity!, insertInto: context)
        //set the entity values
        transc.setValue(Int32(monthlyid), forKey: "monthlyid")
        transc.setValue(mioauthid, forKey: "mioauthid")
        transc.setValue(Int32(empid), forKey: "empid")
        transc.setValue(Int32(doctorid), forKey: "doctorid")

        //save the object
        do {
            try privateMOC.save()
            context.performAndWait {
                do {
                    try context.save()
                    print("total saved Tbl_SchedularDayView in Database!")
                } catch {
                    fatalError("Failure to save context: \(error)")
                }
            }


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

            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }

这就是我如何获取它:

     var drname:[String] = []
   let fetchRequest1:NSFetchRequest<NSFetchRequestResult>  = NSFetchRequest(entityName: "Tbl_SchedularDayView") // 2nd
      do{
              let searchResults = try ServiceCalls.getContext().fetch(fetchRequest1)

               for trans in searchResults as! [NSManagedObject] {
                         drname.append(trans.value(forKey: "mioauthid") as! String)
                 }
             }catch {
               print("Error with request: \(error)")
             }

 print("total docs 1 = ",drname.count," doc names = ",drname)

1 个答案:

答案 0 :(得分:0)

通常会在持久性商店协调员中创建一个moc(懒惰地)并在应用程序的生命周期中挂起。您的privateMOC看起来像是在保存之前(或可能在保存期间)发布的。检查它的寿命。此外,由于您可能正在使用多个MOC,因此请务必遵循CoreData并发规则&amp;已知有效的策略,以保持MOC之间的同步变化。

有关管理您的moc的示例,请参阅此tutorial

如果您要使用多个moc,请在CoreData concurrency上阅读Apple的文档。