gpt4 book ai didi

ios - 如何将数据从iOS中的数据模型存储到核心数据中,并以数据模型的格式获取

转载 作者:行者123 更新时间:2023-11-28 08:23:50 25 4
gpt4 key购买 nike

我想在 iOS 中将数据存储为数据模型。我正在尝试这个,但它不起作用。

我的数据模型类

class FileSaveModel: NSManagedObject {
@NSManaged var id: String
@NSManaged var name: String
@NSManaged var path: String
@NSManaged var time: String
@NSManaged var type: String
@NSManaged var uid: String

// TODO: - Need to get the use of this
// lazy var uidd: NSManagedObjectID = NSManagedObjectID()

override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
}

init(name:String, path: String, contentType: ContentType, entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)

self.path = path
self.name = name
self.type = contentType.rawValue
self.time = "\(NSDate())"
self.uid = "56"
self.id = "789"
}
}

这样保存

func save(name: String, path: String, type: ContentType, modelContent: ModelTest)  {

guard let entity = self.entityWith(name: entityName) else {
return
}

当我尝试用它保存时,它保存了

//let modelFile = FileSaveModel(name: name, path: path, contentType: //type, entity: entity, insertInto: appDelegate.context())

但这会导致错误“无法将 NSManagedObject 转换为 FileSaveModel”

        let model = NSEntityDescription.insertNewObject(forEntityName: entityName, into: appDelegate.context()) as! FileSaveModel

model.name = name
model.path = path
model.type = type.rawValue

save(model: model, modelContent: modelContent)
}

func save(model: FileSaveModel, modelContent: ModelTest) {

do {
try appDelegate.context().save()
print("Save successful")
} catch {
fatalError("Failure to save context: \(error)")
}
}

像这样获取数据但不返回 FileSaveModel 数组只返回 NSManagedObject 数组

func fetchAllModels() {
let fetchItems = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)

do {

let fetchedItems = try appDelegate.context().fetch(fetchItems) as! [FileSaveModel]

if fetchedItems.count>0 {
print(fetchedItems[0].name)
}

} catch {
fatalError("Failed to fetch: \(error)")
}
}

最佳答案

如果我理解你的问题。

选择 xcdatamodeld -> 你的实体 -> 数据模块检查器 -> 模块

如果是当前产品模块,将其更改为全局命名空间

关于ios - 如何将数据从iOS中的数据模型存储到核心数据中,并以数据模型的格式获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40631310/

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