当我请求新数据时,我想在添加新闻之前删除所有记录。有时旧记录的数据和新记录的数据没有变化。
这是我尝试过的,但我的新记录从未保存(始终保存 0 条记录)
当我请求数据时:
Autorisation* aut = [Autorisation MR_createEntity];
// setter method
当我想保存时:
+(void)saveAutorisationList:(NSMutableArray*)autorisationList{
NSManagedObjectContext* localContext = [NSManagedObjectContext MR_defaultContext];
for (Autorisation* aut in [self getAutorisationList]) {
[aut MR_deleteEntityInContext:localContext]; // method that return all Autorisation
}
[localContext MR_saveToPersistentStoreWithCompletion:^(BOOL contextDidSave, NSError * error) {
for (Autorisation* aut in autorisationList) {
[aut MR_inContext:localContext];
}
[localContext MR_saveToPersistentStoreWithCompletion:nil];
}];
}
+(NSMutableArray*)getAutorisationList {
NSManagedObjectContext* localContext = [NSManagedObjectContext MR_defaultContext];
return [[Autorisation MR_findAllInContext:localContext] mutableCopy];
}
最佳答案
这里发生的是您正在删除所有对象,包括您想要保存的对象。以下是逐步发生的事情:
+(void)saveAutorisationList:(NSMutableArray*)autorisationList {
// as it seems, here autorisationList is a list of new objects you want to save.
NSManagedObjectContext* localContext = [NSManagedObjectContext MR_defaultContext];
错误的行为从这里开始:
for (Autorisation* aut in [self getAutorisationList]) {
这里getAutorisationList
获取了当前存在于localContext
中的所有对象,旧的+新的。
[aut MR_deleteEntityInContext:localContext];
// here you deleted each Autorisation object currently existing, including those you want to save
}
...
}
相反,您应该找到您收到的内容与之前存在的内容之间的差异,并仅删除那些未随更新收到的对象。
例如假设您有一组对象 OldSet = {auth1, auth2, auth3}
,并且通过更新您收到了对象 NewSet = {auth2, auth3, auth4}
。
删除的差异是
ToBeDeletedSet = OldSet - NewSet = {auth1}
这样您将保留已有的记录,并保存新的记录。
然后,您的保存方法将如下所示:
+(void)saveAutorisationList:(NSMutableArray*)updatedAutorisationList{
NSManagedObjectContext* localContext = [NSManagedObjectContext MR_defaultContext];
NSMutableArray *oldAutorisationList = [self getAutorisationList];
[oldAutorisationList removeObjectsInArray: updatedAutorisationList];
for (Autorisation* aut in oldAutorisationList) {
[aut MR_deleteEntityInContext:localContext]; // method that return all Autorisation
}
[localContext MR_saveToPersistentStoreWithCompletion:^(BOOL contextDidSave, NSError * error) {
for (Autorisation* aut in updatedAutorisationList) {
[aut MR_inContext:localContext];
}
[localContext MR_saveToPersistentStoreWithCompletion:nil];
}];
}
关于ios - 如何清除实体并在使用神奇记录添加新记录后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435669/