核心数据首次未在实体中保存数据

时间:2016-11-16 13:05:26

标签: ios swift core-data

我正在使用ios中的核心数据开发应用程序。并且有很多实体并且要保存大量数据,这就是为什么我使用"私有上下文"来保存后端线程中的数据的原因。接近和使用块。所有实体都可以,除了一个实体。

在此实体中,第一次启动应用程序并同步数据时不会保存数据,但在此之后,如果我再次同步数据,则会保存该实体中的所有数据。这是我保存数据的代码:

let programAttendeeAssignArray:NSArray? = dict["data_assign"] as AnyObject? as? NSArray
for var paAssignIndex = 0; paAssignIndex < programAttendeeAssignArray?.count; paAssignIndex++ {
    let programAttendeeAssignObj:NSDictionary? = programAttendeeAssignArray?.objectAtIndex(paAssignIndex) as AnyObject? as? NSDictionary
    if let paAssignDict = programAttendeeAssignObj as? [String: AnyObject] {
        var keyString: String = ""
        if let eID = paAssignDict["id"]! as? Int {
            keyString = String(eID)
        }

        let paAssign: Conf_speakers = Utilities.sharedInstance.getOrCreateObjectOfEntityName("Conf_speakers", key: "id", identifier: keyString, localContext: privateContext) as! Conf_speakers

        if let eeid = paAssignDict["id"]! as? Int {
            paAssign.id = String(eeid)
        }

        if let attendee_id = paAssignDict["id1"]! as? Int {
            paAssign.attendee_id = String(attendee_id)
        }

        if let agenda_id = paAssignDict["id2"]! as? Int {
            paAssign.agenda_id = String(agenda_id)
        }

        if let updated_at = paAssignDict["id3"]! as? String {
            paAssign.updated_at = updated_at
        }                       
    }
}

let error: NSErrorPointer = nil
do {
    try privateContext.save()                    
} catch let error1 as NSError {
    error.memory = error1
} catch {
    fatalError()
}

dispatch_async(dispatch_get_main_queue(), {
    appDelegate.managedObjectContext.performBlock { () -> Void in
        //var fds:Bool
        do {
            try
            print("Result MSG: \(appDelegate.managedObjectContext.save())")
            // fds = true
        } catch _ {
            //fds = false
        }
    }
})

1 个答案:

答案 0 :(得分:0)

 let appDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context : NSManagedObjectContext = appDel.managedObjectContext

    let request = NSFetchRequest(entityName: "TableName")
    request.returnsObjectsAsFaults = false
    do {
        var results :NSArray

        try  results = context.executeFetchRequest(request)
        if results.count == 0
        {

        }
        else{

            let managedObject = results[0]
            managedObject.setValue(text, forKey: "TableEntity")
            //save data into table
            try context.save()


        }
    }
    catch{}