如何将函数传递给数据模型的新创建的ManagedObject对象?

时间:2015-05-01 19:18:04

标签: swift core-data nsmanagedobjectcontext

我正在编写一个IOS应用程序,它接收来自用户的数据,我希望将这些数据存储在两个不同用途的数据模型中:

  1. 在临时数据模型(= ReconciliationModel)中,一旦设备具有正在运行的互联网连接,即可与网络服务器同步,并且
  2. 在功能数据模型(= ProgramModel)中,它是ViewController和App beeing能够运行的基础。
  3. 我希望用户能够在没有互联网连接的情况下工作。

    因此,我尝试在将新创建的Reconciliation-ManagedObject(= reconTask)实例保存到第二个函数(= apiCheckCodes)后传递它。不幸的是,这不起作用,我感谢任何帮助。这是代码:

    `func setReconciliationList()->Void {
        let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    let managedObjectContext = appDelegate.managedObjectContext
        let entityDescription = NSEntityDescription.entityForName("ReconciliationModel", inManagedObjectContext: managedObjectContext!)
        let reconTask = ReconciliationModel(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
        reconTask.reconStatus = false
        reconTask.reconType = 2
        reconTask.reconUser = inputTextField.User
        appDelegate.saveContext()    
        // if Internet available ...
        redeemCodes(reconTask.managedObjectContext!)
    }`
    
    func apiCheckCodes(context: context: NSManagedObjectContext)-> Void {
        let fetchRequest = NSFetchRequest(entityName: "ReconciliationModel")
        var requestError: NSError?
        let response = context.executeFetchRequest(fetchRequest, error: &requestError) as [ReconciliationModel!]
        let reconObject = (response as NSArray).lastObject as ReconciliationModel
    
        var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:3000/apicodecheck")!)
        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"
        var params = [
        "user" : ReconObject.user,
        "status" : ReconObject.status,
        "programGoal" : String(ReconObject.programGoal)
        ]
        var error: NSError?
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &error)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
    
        // API Redeem Post request
        var task = session.dataTaskWithRequest(request, completionHandler: { (data, response, err) -> Void in
            var conversionError: NSError?
            var jsonDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves, error: &conversionError) as? NSDictionary
        })
        task.resume()
    }
    

    编辑: 我在第二个函数中找到了一个使用fetchRequest的方法(参见上文)。这是唯一的解决方案吗?

0 个答案:

没有答案