【发布时间】:2018-04-05 12:09:59
【问题描述】:
我无法在 CoreData 中保存对象。它之前工作正常,但我将三个变量从字符串更改为字符串数组...图像、图像描述和属性 我有一个名为 CoreDataHandler 的文件,如下所示。
class CoreDataHandler: NSObject {
private class func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
class func saveObject(name: String, type: String, description: String, image: [String], imageDesc: [String], attrib: [String], rating: String, address: String, lat: Double, long: Double, annoName: String) -> Bool {
//cost: String, openingTimes: String, pets: String,
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "CastleSave", in: context)
let manageObject = NSManagedObject(entity: entity!, insertInto: context)
manageObject.setValue(name, forKey: "name")
manageObject.setValue(type, forKey: "type")
manageObject.setValue(description, forKey: "desc")
manageObject.setValue([image], forKey: "image")
manageObject.setValue([imageDesc], forKey: "imageDesc")
manageObject.setValue([attrib], forKey: "attrib")
manageObject.setValue(rating, forKey: "rating")
manageObject.setValue(address, forKey: "address")
manageObject.setValue(lat, forKey: "lat")
manageObject.setValue(long, forKey: "long")
manageObject.setValue(annoName, forKey: "annoName")
do {
try context.save()
return true
} catch {
return false
}
}
我使用下面的代码保存为收藏夹
CoreDataHandler.saveObject(name: (txte?.name)!, type: (txte?.type)!, description: (txte?.description)!, image: (txte?.image)!, imageDesc: (txte?.imageDesc)!, attrib: (txte?.attrib)!, rating: (txte?.rating)!, address: (txte?.address)!, lat: (txte?.lat)!, long: (txte?.long)!, annoName: (txte?.annoName)!)
在我的数据模型中...
我之前将 image、imageDesc 和 attrib 的属性设置为 String。
我将其更改为 Transformable,并将属性 CustomClass 更改为 [String],但我正在努力了解如何正确保存它。
有人可以帮忙吗?
【问题讨论】:
-
您经常使用类似于
(txte?.name)!的模式,这可能会简化为txte!.name -
究竟是什么问题,崩溃或没有保存或...?
-
您不能直接在
CoreData中保存array。查看可用的数据类型here。检索后使用join函数和separate从数组中创建一个字符串。 -
所以我将所有数据从 GeoJSON 文件加载到 MapView 中。然后,一旦我单击注释,它就会加载适当的数据。这就是 txte 的来源,它基本上是从以前的视图控制器中分离出来的对象。当我按下保存按钮(保存到 coredata)时,Xcode 完全崩溃,我必须重新打开 Xcode。我将图像保存为字符串。
-
不要将图像保存为字符串,而是将图像保存在
documentDirectory并将其路径保存到数据库中。