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

标签 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)")
        }
    }

}

最佳答案

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

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()
    }

}

关于ios - 使用 Swift 插入后,CoreData 文件不显示任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005275/

相关文章:

ios - 将 SF Symbols 系统镜像用于静态 UIApplicationShortcutItem

ios - 如何在两个坐标内显示 map ?

swift - 使用 Alamofire 帖子登录不起作用

ios - 如何将动态数据存入CoreData?

ios - 或者逻辑运算符在 [NSPredicate predicateWithFormat :] 中不起作用

ios - 'NSInternalInconsistencyException',原因 : 'Could not load NIB in bundle: ...' with name

android - 在代号中,一个组合框文本被截断

ios - 有崩溃报告、dsym 文件但没有 ipa/xarchive : How to symbolicate the crash log?

ios - 同时使用滑动手势和触摸开始/移动/结束

ios - 在 ios 中从数组中获取完整的对象