MagicalRecord 并不总是保存更改
Posted
技术标签:
【中文标题】MagicalRecord 并不总是保存更改【英文标题】:MagicalRecord not always save changes 【发布时间】:2015-04-13 05:01:13 【问题描述】:我有UICollectionView
,它从使用 MagicalRecord 从 CoreData 获取数据的数组中填充。我还有按钮“删除”,它必须删除所有选定的单元格及其对象。问题是我的方法正确地删除了数组中的单元格和对象,但没有删除 CoreData。
这是我方法的一部分:
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
__block int counter = 0;
[itemPaths enumerateObjectsUsingBlock:^(NSIndexPath *itemPath, NSUInteger idx, BOOL *stop)
if ( [selectedCellsArray containsObject:[NSString stringWithFormat:@"%lu",(unsigned long)itemPath.row]] )
[indexSet addIndex:itemPath.item];
Content *obj = self.testAssets[itemPath.item];
NSLog(@"deleting asset # %d it is %@ in %lu",(int)idx,obj,(unsigned long)itemPaths.count);
[nsmContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error)
[obj MR_deleteEntity];
if(success)
counter++;
NSLog(@"Entity deleted!");
else
NSLog(@"Entity NOT deleted");
];
];
这是我在日志窗口中方法结束后看到的内容:
-[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x7fb6fbc3db40) Context DEFAULT is about to save. Obtaining permanent IDs for new 3 inserted objects
-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x7fb6fbc3d040) → Saving <NSManagedObjectContext (0x7fb6fbc3d040): *** BACKGROUND SAVING (ROOT) ***> on *** MAIN THREAD ***
-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x7fb6fbc3d040) → Save Parents? 1
-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x7fb6fbc3d040) → Save Synchronously? 0
-[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x7fb6fbc3d040) Context BACKGROUND SAVING (ROOT) is about to save. Obtaining permanent IDs for new 3 inserted objects
__70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x7fb6fbc3d040) → Finished saving: <NSManagedObjectContext (0x7fb6fbc3d040): *** BACKGROUND SAVING (ROOT) ***> on *** BACKGROUND THREAD ***
[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x7fb6fbc3d040) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x7fb6fbc3d040) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
Entity deleted!
Entity NOT deleted
Entity NOT deleted
猜我做错了什么,但无法想象到底是什么。
【问题讨论】:
我知道这是不恰当的评论,但为什么要使用 MR?对 Core Data 的真正理解和实现要强大得多! 【参考方案1】:保存后删除!
MR_saveToPersistentStoreWithCompletion
保存然后运行完成块。
【讨论】:
是不是说我必须先单独删除对象再保存上下文? 您可以删除枚举循环中的所有对象,一旦完成,调用 save 将持久存储的任何更改。以上是关于MagicalRecord 并不总是保存更改的主要内容,如果未能解决你的问题,请参考以下文章
Magical Record 似乎可以保存,但如果应用程序终止,更改会丢失