我的coredata模型中有不同的属性,如运费方式,因子模式等,如下图所示......
我有一个名为Shipping
的实体,其属性为shipping method
,factor
,mode
,transport
。由于这些价值观不同,我感到困惑......
保存到coredata后,我的第一个对象的SHIP BY AIR(ELOC)
shipping method
值为40
Factor
,AIR
Mode
等......
如果它是一个单一的价值,那么我本可以这样做......
do {
let managedContext = persistentContainer.viewContext
let newitem = NSEntityDescription.insertNewObject(forEntityName: "Values", into: managedContext)
newitem.setValue("12",forKey: "custom")
newitem.setValue("0.5",forKey: "ibaseCost")
self.valueDetails.append(newitem as! Values)
try managedContext.save()
} catch {
}
但在我目前的情况下,我如何存储到Coredata ......?
答案 0 :(得分:1)
将数据添加到核心数据:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let ship = Shipping(context: context) // Link Task & Context
ship.shippingmethod = "yourvalue"
ship.factor = "yourvalue"
ship.mode = "yourvalue"
ship.transport = "yourvalue"
// Save the data to coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()
如果您的问题只是存储,这将解决它
希望这有帮助。
var shippindData = [
["shippingMethod":"ELOC","Factor":40,"Mode":"AIR","Transport":"Y"],
["shippingMethod":"VLOC","Factor":40,"Mode":"AIR","Transport":"Y"],
["shippingMethod":"ELOC","Factor":35,"Mode":"MIXED MODE","Transport":"Y"]]
for data in shippindData{
let innerData = data as! [String:Any]
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let ship = Shipping(context: context) // Link Task & Context
ship.shippingmethod = innerData["shippingMethod"]
ship.factor = innerData["Factor"]
ship.mode = innerData["Mode"]
ship.transport = innerData["Transport"]
// Save the data to coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
您可以使用此逻辑创建这样的数据,并使用for-loop
答案 1 :(得分:0)
希望此解决方案可以帮助您
为您的实体创建托管目标文件
<强>夫特强>:
public class YourEntityName: NSManagedObject {
@NSManaged public var custom: String
}
ObjC :
@interface YourEntityName : NSManagedObject
@property (nullable, nonatomic, retain) NSString * custom; //follow the same for other columns
@end
@implementation YourEntityName
@dynamic custom; //follow the same for other columns
@end
只需在swift / Obj C文件中添加managedObject的属性即可。如果要保存,请使用代码段
YourEntityName = NSEntityDescription.insertNewObject(forEntityName: ",into: "YourEntityName" appDelegateObject.managedObjectContext) as! YourEntityName
YourEntityName.entity1 = "1"
YourEntityName.entity2 = "2"
YourEntityName.entity3 = "3"
YourEntityName.entity4 = "4"
self.yourManagedDelegateObject.saveContext()
确保使用coreData托管对象包装类