【问题标题】:Why iOS app is throwing error as 'An NSManagedObject of class 'MYOWEB.SearchHistory' must have a valid NSEntityDescription.' in swift?为什么 iOS 应用程序会抛出错误,因为“类 'MYOWEB.SearchHistory' 的 NSManagedObject 必须具有有效的 NSEntityDescription。”迅速?
【发布时间】:2021-10-02 11:38:31
【问题描述】:

我正在使用核心数据来保存我定义了我的实体的数据,但是当我调用我的 saveData 函数时,应用程序崩溃并抛出错误:由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:''MYOWEB.SearchHistory' 类的 NSManagedObject 必须具有有效的 NSEntityDescription。' 以 NSException 类型的未捕获异常终止

func saveData(name: String) {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let newItem = SearchHistory(context: context)
    newItem.name = name
    newItem.created_at = Date()
    do {
        try context.save()
    } catch {
        let nserror = error as NSError
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
    }
}

我的实体

子类文件

//
//  SearchHistory+CoreDataClass.swift
//  MYOWEB
//
//  Created by developer on 7/26/21.
//
//

import Foundation
import CoreData


public class SearchHistory: NSManagedObject {

}


//
//  SearchHistory+CoreDataProperties.swift
//  MYOWEB
//
//  Created by developer on 7/26/21.
//
//

import Foundation
import CoreData


extension SearchHistory {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<SearchHistory> {
        return NSFetchRequest<SearchHistory>(entityName: "SearchHistory")
    }

    @NSManaged public var created_at: Date?
    @NSManaged public var name: String?

}

【问题讨论】:

标签: ios swift xcode core-data


【解决方案1】:

哎呀!在 appDelegate 中给定了不正确的容器名称,出现了一个小错误

`let container = NSPersistentContainer(name: "MyoWeb_iOS")`

替换上面的代码就可以了

let container = NSPersistentContainer(name: "MYOWEB")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2018-12-06
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多