将数据保存到Core Data数据库或从Core Data数据库加载数据(iOS 8)

时间:2015-01-13 19:32:28

标签: ios uitableview swift core-data

首先,我必须说我是iOS编程的新手。我用Swift开发和核心数据应用程序。我有一个名为tanningarTableViewController的UITableViewController,我想要显示数据,数据将被添加(保存)在另一个名为“nyTankning”的ViewController中。

我已经关注了Youtube上的教程,但由于Swift在WWDC期间发生了变化,我有时不得不寻找其他苏丹。 我不是100%肯定UITableViewController编码正确,但我猜,因为看起来问题是保存?我读过一些NSFetchedController或类似的内容,我应该使用它吗?

以下是我希望保存数据的按钮:

 @IBAction func saveButton(sender: AnyObject) {

    // Reference to out app delegate

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate

    // Reference moc
    let contxt: NSManagedObjectContext = appDel.managedObjectContext!
    let en = NSEntityDescription.entityForName("Tankningslista", inManagedObjectContext: contxt)



    // Create instance of our data model and initialize 
    var nyTankning = Model(entity: en!, insertIntoManagedObjectContext: contxt)

    // Map our properies
    nyTankning.liter = (textFieldLiter.text as NSString).floatValue
    nyTankning.kronor = (textFieldKronor.text as NSString).floatValue
    nyTankning.literpris = (textFieldLiterpris.text as NSString).floatValue


    // Save or context
    contxt.save(nil)

    println(nyTankning.liter)
    println(nyTankning.kronor)
    println(nyTankning.literpris)


    if contxt.save(nil) {

        // Fetch the Data from Core Data first....
        let fetchRequest = NSFetchRequest(entityName: "Tankningslista")
        var error:NSError?
        var result: NSArray = contxt.executeFetchRequest(fetchRequest, error: nil)!


        for res in result {

            // Now you can display the data

            println(res.liter)
            println(res.kronor)
            println(res.literpris)

        }

        // End of the fetching

    } else {
         println("error")
    }

    // navigate back to root vc
    self.navigationController?.popToRootViewControllerAnimated(true)

}

这是UITableViewController的代码

   import UIKit
   import CoreData

   class tankningarTableViewController: UITableViewController {

       var Tankningar: Array<AnyObject> = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

}

override func viewDidAppear(animated: Bool) {
    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let contxt:NSManagedObjectContext = appDel.managedObjectContext!
    let freq = NSFetchRequest(entityName: "Tankningslista")

    var error :NSError?

    let fetchedResults = contxt.executeFetchRequest(freq, error: &error) as? [NSManagedObject]
    if let results = fetchedResults { Tankningar = results
    }
    else
    { 
     println("Could not fetch \(error)")   
    }

    tableView.reloadData()

    println(Tankningar)
    println("freq")
    println(freq)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return Tankningar.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Configure the cell...

    let CellID: NSString = "Cell"

    var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell


    let fetchRequest = NSFetchRequest(entityName: "Tankningslista")

    var data: NSManagedObject = Tankningar[indexPath.row] as NSManagedObject

    var literLabel = data.valueForKeyPath("liter") as? String
    var kronorLabel = data.valueForKeyPath("kronor") as? String
    var literprisLabel = data.valueForKeyPath("literpris") as? String

    cell.textLabel?.text = data.valueForKeyPath("liter") as? String

    return cell
}

当我检查调试器时,我在TableViewController中创建的数组似乎是空的:

 []
freq
 <NSFetchRequest: 0x7ffd4ad24830> (entity: Tankningslista; predicate: ((null));     sortDescriptors: ((null)); type: NSManagedObjectResultType; )
34.0
551.0
14.0
39.0
551.0
14.0
[, ]
freq
<NSFetchRequest: 0x7ffd4ae8c330> (entity: Tankningslista; predicate: ((null)); sortDescriptors: ((null)); type: NSManagedObjectResultType; )

有什么问题?

0 个答案:

没有答案