我从Web服务获取数据,然后使用Core Data存储。 当我从Web服务获取新数据时,它包含我已存储的数据。 在核心数据中,我存储Web服务提供的每个数据集的唯一ID。 在我当前的实现中,我只存储具有唯一ID的集合的多个实例。但我希望现有的一个保留,新的一个被忽略。或者,因为它们无论如何都是相同的,新的覆盖现有的。 这会是什么方法?
由于
答案 0 :(得分:0)
class func defaultInsert(data:[String:Any]) -> AppLabels {
var label = self.fetchLabelFromLabelUsingVarID(var_id: data["var_id"] as! String,screen: data["name"] as! String)
if label == nil{
label = NSEntityDescription.insertNewObject(forEntityName: "AppLabels", into: CoreDataStack.managedObjectContext) as? AppLabels
}
if data["var_id"] != nil {
label?.var_id = data["var_id"] as? String
}
if data["name"] != nil {
label?.name = data["name"] as? String
}
if data["value"] != nil {
label?.value = data["value"] as? String
}
if data["var_name"] != nil {
label?.var_name = data["var_name"] as? String
}
return label!;
}
class func fetchLabelFromLabelUsingVarID (var_id:String,screen:String) -> AppLabels? {
let fetchrequest = NSFetchRequest<AppLabels>(entityName: "AppLabels")
fetchrequest.predicate = NSPredicate(format: "var_id == %@ && name == %@", var_id,screen);
fetchrequest.fetchLimit = 1;
do {
let fetchedResults = try CoreDataStack.managedObjectContext.fetch(fetchrequest)
if let applabel = fetchedResults.first {
return applabel
}
}
catch{
}
return nil;
}
答案 1 :(得分:0)
首先,您必须使用uniqID检查数据库中是否存在来自API的新对象。如果是,则如果无法获取,则将旧对象覆盖为新对象。
关注示例代码可能会对您有所帮助
//MARK:- get if ClassRoom Exist
func getClassroom(_ classRooMID:String) -> Classroom? {
var allClassroom:[Classroom]!
let request = Classroom.getFetchRequest()
let keyVal = classRooMID
request.predicate = NSPredicate.init(format: "classroomid = %@", argumentArray: [keyVal])
do {
allClassroom = try managedObjectContext.fetch(request) as! [Classroom]
}
catch let error as NSError{
// failure
print("Fetch failed: \(error.localizedDescription)")
}
if allClassroom.count != 0 {
return allClassroom[0]
}
return nil
}
插入新对象时
//MARK:- InsertClassroom Data
func insertClassroomData(_ classRoomDict:NSDictionary) -> Classroom {
let keyValue = classRoomDict[KEY_CLASS_ROOM_ID] as! String
var classroomObj = self.getClassroom(keyValue)
if (classroomObj == nil){
classroomObj = NSEntityDescription.insertNewObject(forEntityName: "Classroom", into: managedObjectContext) as? Classroom
}
classroomObj!.setClassroomFromDict(classRoomDict)
return classroomObj!
}
谢谢