从Core Data

时间:2017-06-24 07:08:49

标签: swift core-data swift3

我保存了一些数据 - 名字和姓氏。但我不知道如何获取一些数据。 这是我的代码,但我不知道它为什么不起作用 - 我不知道

class UserIN: NSManagedObject {

    @NSManaged var name: String?

}

我创建了NSManagedObject Subclass

func fetching(){
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let usersFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

        do {
            let fetchedUsers = try context.fetch(usersFetch) as! [UserIN]
            print(fetchedUsers)
        } catch {
            fatalError("Failed to fetch employees: \(error)")
        }

    }

请告诉我它没有显示提取数据的原因。

1 个答案:

答案 0 :(得分:0)

NSManagedObject子类的类必须与实体名称匹配(除非您在Interface Builder中手动更改)

class Users: NSManagedObject {

    @NSManaged var name: String?

}

与问题无关但在Swift 3中使用静态类型的获取请求而不是通用NSFetchRequestResult

func fetching(){
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let usersFetch = NSFetchRequest<Users>(entityName: "Users")

    do {
        let fetchedUsers = try context.fetch(usersFetch)
        print(fetchedUsers)
    } catch {
        fatalError("Failed to fetch employees: \(error)")
    }

}
相关问题