gpt4 book ai didi

ios - 为什么 insertNewObjectForEntityForName 只返回一个 NSManagedObject?

转载 作者:IT王子 更新时间:2023-10-29 05:29:04 25 4
gpt4 key购买 nike

我正在尝试将一些 RubyMotion 代码移至 Swift。到目前为止它有效。我不明白的是为什么不能将以下结果转换为 Document 类:

var newObject : NSManagedObject 
NSEntityDescription.insertNewObjectForEntityForName("Document", inManagedObjectContext:context)
as NSManagedObject

insertNewObjectForEntityForName 调用返回一个 NSManagedObject 类型的对象。但为什么 insertNewObjectForEntityForName 不返回由 entity.managedObjectClassName 指定的 Document 类型的对象?

我的实体看起来像这样:

func DocumentEntity () -> NSEntityDescription {

var entity = NSEntityDescription()
entity.name = "Document"
entity.managedObjectClassName = "Document"

var property = NSAttributeDescription()
property.name = "title"
property.attributeType = NSAttributeType.StringAttributeType
property.optional = false

entity.properties = [property]

return entity
}

class Document : NSManagedObject {
@NSManaged var title : String
}

model = NSManagedObjectModel()
model.entities = [DocumentEntity()]

var store = NSPersistentStoreCoordinator(managedObjectModel: model)

最佳答案

您需要将 @objc(Document) 添加到您的 Document 类中。这样 Core Data(仍在 Objective-C 中)就可以处理您的 Swift 类。

@objc(Document)
class Document : NSManagedObject {
@NSManaged var title : String
}

然后就可以了:

var document = NSEntityDescription.insertNewObjectForEntityForName("Document", inManagedObjectContext: context) as Document

将返回正确的类型

关于ios - 为什么 insertNewObjectForEntityForName 只返回一个 NSManagedObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24105120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com