在一个MOC中删除的核心数据模型对象仍可用于另一个

时间:2016-06-01 05:49:25

标签: core-data fault

这是对Apple的Core Data PG部分测试,我在这里引用

  
      
  • 您开始使用应用程序中另一个对象的托管对象的强引用。
  •   
  • 您通过托管对象上下文删除了托管对象。
  •   
  • 您保存了对象上下文的更改。   此时,已删除的对象已变为故障。它不会被破坏,因为这样做会违反内存管理规则。   Core Data将尝试实现故障托管对象,但由于该对象已从商店中删除,因此无法执行此操作。也就是说,商店中不再存在具有相同全局ID的对象。
  •   

所以我设置test project以查看它是否是真实案例。

我正在使用MagicalRecord来节省创建MOC的麻烦,代码基于名为“People”的Core数据模型类

@interface People : NSManagedObject
@property (nonatomic) int64_t userID;
@property (nullable, nonatomic, retain) NSString *name;

@end

在测试部分中,我将创建的MOCs MagicalRecord包装到backgroundMOC和UIMOC中,以便那些不熟悉MagicalRecord的人不会感到困惑。

UIMOC是BackgroundMOC的子项,将通过监听NSManagedObjectContextDidSaveNotification backgroundMOC发送来合并backgroundMOC的更改。

“saveWithBlockAndWait”只是“performBlockAndWait”的包装。所以来了,

[[self backgroundMOC] MR_saveWithBlockAndWait:^(NSManagedObjectContext * _Nonnull localContext) {
    People *people = [People MR_createEntityInContext:localContext];
    people.userID = 1;
    people.name = @"Joey";
}];

People *peopleInMainThread = [People MR_findFirstInContext:[self UIMOC]];

NSLog(@"Before delete, name = %@", peopleInMainThread.name);

[[self backgroundMOC] MR_saveWithBlockAndWait:^(NSManagedObjectContext * _Nonnull localContext) {
    People *people = [People MR_findFirstInContext:localContext];
    NSLog(@"Deleting, name = %@", people.name);
    [localContext deleteObject:people];
}];

NSLog(@"After delete, name = %@", peopleInMainThread.name);

[[self UIMOC] save:nil];

NSLog(@"After save UIMOC, name = %@", peopleInMainThread.name);

NSLog结果是

Before delete, name = Joey     //As expected
Deleting, name = Joey          //As expected
After delete, name = Joey      //Shouldn't it be nil already? 
After save UIMOC, name = null  //As expected

这个结果似乎表明来自父MOC的合并不会使模型对象出错,这可能导致一些难以发现的错误,或者在任何地方导致繁琐的检查代码。 再次与人物对象。我必须做这样的事情

- (void)codesInSeriousApp
{
[[self backgroundMOC] MR_saveWithBlockAndWait:^(NSManagedObjectContext * _Nonnull localContext) {
    People *people = [People MR_createEntityInContext:localContext];
    people.userID = 1;
    people.name = @"Joey";
}];

__block People *people = nil;
[[self UIMOC] performBlockAndWait:^{
    people = [People MR_findFirstInContext:[self UIMOC]];
}];

[self sendHttpRequestViaAFNetworking:^{
    //this block is executed on main thread, which is AFNetworking's default behavior
    if ([[self UIMOC] existingObjectWithID:people.objectID error:NULL])//[people isFault] would be NO here, and people's properties stay still.
    {
        //do something
    }
    else
    {
        //the people object is gone
        //maybe some codes on another thread deleted it and save to the backgroundMOC
        //the UIMOC merge the changes sent by notification, but the people object is still NOT FAULT!
    }
}];
}

据我所知,对于特定MOC中的任何模型非故障对象,比如说MOCA,在[MOC save:& error]一直调用到持久性存储之前,该对象不会出错。 让我感到困惑的是,如果另一个MOC已经通过执行保存链已经知道对象是错误的,并且MOCA合并了MOC发出的变化,那么它中的对象怎么仍然是非故障的呢? 我误解了还是什么?任何回复都将不胜感激。

提前Thx:)

0 个答案:

没有答案