使用Swift插入后,CoreData文件不显示任何数据

时间:2016-08-17 19:59:53

标签: ios swift core-data

我正在尝试使用coredata和swift插入简单数据,下面是我的代码,但是当我运行它并打开我的sqlite文件时,我可以看到它中没有数据?,任何请帮助出错的地方。

import UIKit
import CoreData

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

        print(documentsPath)

        self.saveName("John")

    }

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

    func saveName(name: String) {
        //1
        let appDelegate =
            UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext

        //2
        let entity =  NSEntityDescription.entityForName("Persons",
                                                        inManagedObjectContext:managedContext)

        let person = NSManagedObject(entity: entity!,
                                     insertIntoManagedObjectContext: managedContext)

        //3
        person.setValue(name, forKey: "name")

        //4
        do {
            try managedContext.save()
            //5
            //people.append(person)
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    }

}

1 个答案:

答案 0 :(得分:1)

尝试更像这样的东西。您拥有的代码将用于更新和添加。

func saveName(name: String) {
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext
    let newItem = NSEntityDescription.insertNewObjectForEntityForName("Persons", inManagedObjectContext: context) as! Persons
    newItem.person = name
    do {
        try context.save()
    } catch let error as NSError {

        print("Unresolved error \(error), \(error.userInfo)")
        abort()
    }

}