sqlite 检索实体名称时崩溃?

laik7k3q  于 2022-11-30  发布在  SQLite
关注(0)|答案(5)|浏览(134)

当我的应用程序第一次启动时,我做了一些第一次设置配置,这是使用CoreData API和JSON文档中的数据来播种我的SQLLite数据库。
我首先从核心数据堆栈中获取对托管对象上下文的引用,然后调用一个执行JSON配置的方法。

....(JSON conversion)....

context.perform {
 _ = Exercise.insert(into: context, name: exerciseName, category: categoryNumber, equipment: equipment, skill: "", primaryMuscle: primaryMuscle, otherMuscles: otherMuscles, info: exerciseDescription, image1: exerciseImage1, image2: exerciseImage2)
   }

在每次迭代中,当i循环遍历JSON对象时,它会持久化每个对象。
插入对象的方法如下:

public static func insert(into context: NSManagedObjectContext, name: String, category: Int16, equipment: String?, skill: String?, primaryMuscle: String?, otherMuscles: String?, info: String?, image1: String?, image2: String?) -> Exercise {
    let exercise: Exercise = context.insertObject()
    exercise.name = name
    exercise.category = category
    exercise.info = info
    exercise.primaryMuscle = primaryMuscle
    exercise.otherMuscles = otherMuscles
    exercise.equipment = equipment
    exercise.skill = skill

    if image1 != nil {
        exercise.image1Path = image1
    }

    if image2 != nil {
        exercise.image2Path = image2
    }

    return exercise
}

然后我扩展了NSManagedObjectContext...

extension NSManagedObjectContext {
public func insertObject<Object: NSManagedObject>() -> Object where Object: Managed {
    guard let obj = NSEntityDescription.insertNewObject(forEntityName: Object.entityName, into: self) as? Object else { fatalError("Wrong object type") }
    return obj
}
}

这是我对“托管”协议的声明:

public protocol Managed: class, NSFetchRequestResult {
static var entityName: String {get}
....
   }

extension Managed where Self: NSManagedObject {
public static var entityName: String { return entity().name! }
 }

然后,当我尝试从我试图插入对象的协议扩展中检索entityName时崩溃...

它给我错误“致命错误:展开可选值时意外找到nil”
我没有生成我的NSManagedObjectSublcasses,我自己创建了它们,但我确信我做得正确。我有一种感觉,尽管当应用程序运行时,Core Data没有为“Exercise”选择我的Model类。这就是为什么实体名称不返回任何内容的原因。下面是我的model类的代码:

import UIKit
import CoreData

public class Exercise: NSManagedObject {

@NSManaged public fileprivate(set) var category: Int16
@NSManaged public fileprivate(set) var image1Path: String?
@NSManaged public fileprivate(set) var image2Path: String?
@NSManaged public fileprivate(set) var equipment: String?
@NSManaged public fileprivate(set) var info: String?
@NSManaged public fileprivate(set) var skill: String?
@NSManaged public fileprivate(set) var primaryMuscle: String?
@NSManaged public fileprivate(set) var otherMuscles: String?

public static let normalizedNameKey = "name_normalized"

@NSManaged fileprivate var primitiveName: String

public var name: String {
    set {
        willChangeValue(forKey: #keyPath(Exercise.name))
        primitiveName = newValue
        updateNormalizedName(newValue)
        didChangeValue(forKey: #keyPath(Exercise.name))
    }
    get {
        willAccessValue(forKey: #keyPath(Exercise.name))
        let value = primitiveName
        didAccessValue(forKey: #keyPath(Exercise.name))
        return value
    }
}

fileprivate func updateNormalizedName(_ name: String) {
    setValue(name.normalizedForSearch, forKey: Exercise.normalizedNameKey)
}

public var exerciseImage1: UIImage? {
    guard let image = image1Path else {return nil}
    return UIImage(named: image)
}

public var exerciseImage2: UIImage? {
    guard let image = image2Path else {return nil}
    return UIImage(named: image)
}

 public static func insert(into context: NSManagedObjectContext, name: String, category: Int16, equipment: String?, skill: String?, primaryMuscle: String?, otherMuscles: String?, info: String?, image1: String?, image2: String?) -> Exercise {
    let exercise: Exercise = context.insertObject()
    exercise.name = name
    exercise.category = category
    exercise.info = info
    exercise.primaryMuscle = primaryMuscle
    exercise.otherMuscles = otherMuscles
    exercise.equipment = equipment
    exercise.skill = skill

    if image1 != nil {
        exercise.image1Path = image1
    }

    if image2 != nil {
        exercise.image2Path = image2
    }

    return exercise
}

}

  extension Exercise: Managed {

  public static var defaultSortDescriptors: [NSSortDescriptor] {
    return [NSSortDescriptor(key: #keyPath(name), ascending: false)]
  }

public static func defaultPredicate(muscleCategory: Int) -> NSPredicate 
 {
    return NSPredicate(format: "%K == %ld", 
 #keyPath(Exercise.category), muscleCategory)
}
}

下面是数据模型编辑器中的实体:

知道哪里出了问题吗?谢谢

9avjhtql

9avjhtql1#

我有完全相同的问题,使用完全相同的代码(核心数据书由弗洛里安库格勒)。
我的问题出现后,我添加了一个新的实体+关系,当创建新的实体,实体名称是零。
我通过删除实体并重新创建来修复它。错误消失了。

ddrv8njm

ddrv8njm2#

也许这是个不好的主意,但现在可以避免坠机了......等待更好的解决方案。
雨燕4:

extension NSObject {
    var className: String {
        return String(describing: type(of: self))
    }

    class var className: String {
        return String(describing: self)
    }
}

然后

static var entityName: String {
    return self.className //insead of `entity().name!`
}
idv4meu8

idv4meu83#

莫因,
首先展开可选值。

public static var entityName: String 
    { 
        if let _returnName = entity().name{
            return _returnName
        }else
        {
            return nil
        } 
   }
}

Optional Chaining
核心数据:
课程练习
当您更改dbModel并执行“Create NSManagedObject Sub..”时,练习中的所有函数都将被覆盖。
使用单独的类,如类ExerciseExtension

import UIKit
import CoreData

extension Exercise {
  func setName(name : String)
  {
    self.name = name
  }
  .....
}
x3naxklr

x3naxklr4#

我在Florian Kugler的Core Data书中也遇到了同样的问题。不幸的是,@科比的答案没有帮助。我通过在Core Data模型的文件检查器中选择类的模块来解决这个问题。

它以前设置为“无”。

shyt4zoc

shyt4zoc5#

我在iOS 10.3+上使用Xcode 9.4.1的Swift 4.1项目上也遇到了类似的问题,我试着做了这样的事情:

guard let description = Entity.entity(),
  throw Error.entityNotFound
}
// *[some code]*
context.perform {
// *[some code]*
}

但是我的一些单元测试失败了,其他的运行得很好。我的xcdatamodelNSManagedObject子类都很好。最后,我通过检索perform闭包中的实体名称使它运行起来:

context.perform {
  guard let description = Entity.entity(),
    throw Error.entityNotFound
  }
// *[some code]*
}

相关问题