71

我有一个NSManagedObject已被删除的,并且包含该托管对象的上下文已被保存。我知道如果 Core Data 将在下一次保存操作期间要求持久存储删除对象,则isDeleted返回。YES但是,由于保存已经发生,因此isDeleted返回NO

在保存包含上下文之后NSManagedObject,判断一个是否已被删除的好方法是什么?

(如果您想知道为什么引用已删除托管对象的对象还不知道删除,那是因为删除和上下文保存是由后台线程发起的,该线程使用 执行删除和保存performSelectorOnMainThread:withObject:waitUntilDone:。)

4

5 回答 5

94

检查托管对象的上下文似乎有效:

if (managedObject.managedObjectContext == nil) {
    // Assume that the managed object has been deleted.
}

从 Apple 的文档中managedObjectContext...

如果接收者已从其上下文中删除,则此方法可能返回 nil。

如果接收器出现故障,则调用此方法不会导致其触发。

这两个似乎都是好事。

更新:如果您尝试测试专门检索的托管对象是否objectWithID:已被删除,请查看Dave Gallagher 的答案。他指出,如果您objectWithID:使用已删除对象的 ID 调用,则返回的对象将是一个将其managedObjectContext设置为 nil 的错误。因此,您不能简单地检查它managedObjectContext来测试它是否已被删除。existingObjectWithID:error:如果可以,请使用。如果不是,例如,您的目标是 Mac OS 10.5 或 iOS 2.0,则需要执行其他操作来测试是否删除。有关详细信息,请参阅他的答案

于 2010-12-02T22:35:35.110 回答
43

更新:一个改进的答案,基于James Huddleston在下面讨论中的想法。

- (BOOL)hasManagedObjectBeenDeleted:(NSManagedObject *)managedObject {
    /*
     Returns YES if |managedObject| has been deleted from the Persistent Store, 
     or NO if it has not.

     NO will be returned for NSManagedObject's who have been marked for deletion
     (e.g. their -isDeleted method returns YES), but have not yet been commited 
     to the Persistent Store. YES will be returned only after a deleted 
     NSManagedObject has been committed to the Persistent Store.

     Rarely, an exception will be thrown if Mac OS X 10.5 is used AND 
     |managedObject| has zero properties defined. If all your NSManagedObject's 
     in the data model have at least one property, this will not be an issue.

     Property == Attributes and Relationships

     Mac OS X 10.4 and earlier are not supported, and will throw an exception.
     */

    NSParameterAssert(managedObject);
    NSManagedObjectContext *moc = [self managedObjectContext];

    // Check for Mac OS X 10.6+
    if ([moc respondsToSelector:@selector(existingObjectWithID:error:)])
    {
        NSManagedObjectID   *objectID           = [managedObject objectID];
        NSManagedObject     *managedObjectClone = [moc existingObjectWithID:objectID error:NULL];

        if (!managedObjectClone)
            return YES;                 // Deleted.
        else
            return NO;                  // Not deleted.
    }

    // Check for Mac OS X 10.5
    else if ([moc respondsToSelector:@selector(countForFetchRequest:error:)])
    {
        // 1) Per Apple, "may" be nil if |managedObject| deleted but not always.
        if (![managedObject managedObjectContext])
            return YES;                 // Deleted.


        // 2) Clone |managedObject|. All Properties will be un-faulted if 
        //    deleted. -objectWithID: always returns an object. Assumed to exist
        //    in the Persistent Store. If it does not exist in the Persistent 
        //    Store, firing a fault on any of its Properties will throw an 
        //    exception (#3).
        NSManagedObjectID *objectID             = [managedObject objectID];
        NSManagedObject   *managedObjectClone   = [moc objectWithID:objectID];


        // 3) Fire fault for a single Property.
        NSEntityDescription *entityDescription  = [managedObjectClone entity];
        NSDictionary        *propertiesByName   = [entityDescription propertiesByName];
        NSArray             *propertyNames      = [propertiesByName allKeys];

        NSAssert1([propertyNames count] != 0, @"Method cannot detect if |managedObject| has been deleted because it has zero Properties defined: %@", managedObject);

        @try
        {
            // If the property throws an exception, |managedObject| was deleted.
            (void)[managedObjectClone valueForKey:[propertyNames objectAtIndex:0]];
            return NO;                  // Not deleted.
        }
        @catch (NSException *exception)
        {
            if ([[exception name] isEqualToString:NSObjectInaccessibleException])
                return YES;             // Deleted.
            else
                [exception raise];      // Unknown exception thrown.
        }
    }

    // Mac OS X 10.4 or earlier is not supported.
    else
    {
        NSAssert(0, @"Unsupported version of Mac OS X detected.");
    }
}

旧/已弃用的答案:

我写了一个稍微好一点的方法。self是您的核心数据类/控制器。

- (BOOL)hasManagedObjectBeenDeleted:(NSManagedObject *)managedObject
{
    // 1) Per Apple, "may" be nil if |managedObject| was deleted but not always.
    if (![managedObject managedObjectContext])
        return YES;                 // Deleted.

    // 2) Clone |managedObject|. All Properties will be un-faulted if deleted.
    NSManagedObjectID *objectID             = [managedObject objectID];
    NSManagedObject   *managedObjectClone   = [[self managedObjectContext] objectWithID:objectID];      // Always returns an object. Assumed to exist in the Persistent Store. If it does not exist in the Persistent Store, firing a fault on any of its Properties will throw an exception.

    // 3) Fire faults for Properties. If any throw an exception, it was deleted.
    NSEntityDescription *entityDescription  = [managedObjectClone entity];
    NSDictionary        *propertiesByName   = [entityDescription propertiesByName];
    NSArray             *propertyNames      = [propertiesByName allKeys];

    @try
    {
        for (id propertyName in propertyNames)
            (void)[managedObjectClone valueForKey:propertyName];
        return NO;                  // Not deleted.
    }
    @catch (NSException *exception)
    {
        if ([[exception name] isEqualToString:NSObjectInaccessibleException])
            return YES;             // Deleted.
        else
            [exception raise];      // Unknown exception thrown. Handle elsewhere.
    }
}

正如James Huddleston在他的回答中提到的,检查 NSManagedObject 的-managedObjectContext返回nil是否是查看缓存/陈旧 NSManagedObject 是否已从 Persistent Store 中删除的“非常好的”方式,但它并不总是准确的,正如 Apple 在他们的文档中所说:

如果接收者已从其上下文中删除,则此方法可能返回 nil。

什么时候不会返回零?如果您使用已删除的 NSManagedObject 获取不同的 NSManagedObject,-objectID如下所示:

// 1) Create a new NSManagedObject, save it to the Persistant Store.
CoreData        *coreData = ...;
NSManagedObject *apple    = [coreData addManagedObject:@"Apple"];

[apple setValue:@"Mcintosh" forKey:@"name"];
[coreData saveMOCToPersistentStore];


// 2) The `apple` will not be deleted.
NSManagedObjectContext *moc = [apple managedObjectContext];

if (!moc)
    NSLog(@"2 - Deleted.");
else
    NSLog(@"2 - Not deleted.");   // This prints. The `apple` has just been created.



// 3) Mark the `apple` for deletion in the MOC.
[[coreData managedObjectContext] deleteObject:apple];

moc = [apple managedObjectContext];

if (!moc)
    NSLog(@"3 - Deleted.");
else
    NSLog(@"3 - Not deleted.");   // This prints. The `apple` has not been saved to the Persistent Store yet, so it will still have a -managedObjectContext.


// 4) Now tell the MOC to delete the `apple` from the Persistent Store.
[coreData saveMOCToPersistentStore];

moc = [apple managedObjectContext];

if (!moc)
    NSLog(@"4 - Deleted.");       // This prints. -managedObjectContext returns nil.
else
    NSLog(@"4 - Not deleted.");


// 5) What if we do this? Will the new apple have a nil managedObjectContext or not?
NSManagedObjectID *deletedAppleObjectID = [apple objectID];
NSManagedObject   *appleClone           = [[coreData managedObjectContext] objectWithID:deletedAppleObjectID];

moc = [appleClone managedObjectContext];

if (!moc)
    NSLog(@"5 - Deleted.");
else
    NSLog(@"5 - Not deleted.");   // This prints. -managedObjectContext does not return nil!


// 6) Finally, let's use the method I wrote, -hasManagedObjectBeenDeleted:
BOOL deleted = [coreData hasManagedObjectBeenDeleted:appleClone];

if (deleted)
    NSLog(@"6 - Deleted.");       // This prints.
else
    NSLog(@"6 - Not deleted.");

这是打印输出:

2 - Not deleted.
3 - Not deleted.
4 - Deleted.
5 - Not deleted.
6 - Deleted.

如您所见,-managedObjectContext如果 NSManagedObject 已从 Persistent Store 中删除,则不会总是返回 nil。

于 2011-10-25T21:55:33.083 回答
29

我担心其他答案中的讨论实际上隐藏了正确答案的简单性。在几乎所有情况下,正确答案是:

if ([moc existingObjectWithID:object.objectID error:NULL])
{
    // object is valid, go ahead and use it
}

此答案不适用的唯一情况是:

  1. 如果您的目标是 Mac OS 10.5 或更早版本
  2. 如果您的目标是 iOS 2.0 或更早版本
  3. 如果对象/上下文尚未保存(在这种情况下,您要么不在乎,因为它不会抛出 a NSObjectInaccessibleException,要么您可以使用object.isDeleted
于 2013-07-31T12:10:35.307 回答
15

由于我最近在依赖 Core Data 的 iOS 应用程序中实现 iCloud 的经验,我意识到最好的方法是观察框架的通知。至少,比依赖一些可能会或可能不会告诉您是否删除了某些托管对象的晦涩方法要好。

对于“纯”核心数据应用程序,您应该在主线程上观察NSManagedObjectContextObjectsDidChangeNotification 。通知的用户信息字典包含插入、删除和更新的托管对象的 objectID 集。

如果您在其中一组中找到托管对象的 objectID,那么您可以以某种不错的方式更新您的应用程序和 UI。

就是这样...有关更多信息,请查看 Apple 的 Core Data Programming Guide,Concurrency with Core Data 一章。有一节“使用通知跟踪其他线程中的更改”,但不要忘记查看上一节“使用线程限制支持并发”。

于 2012-01-12T01:11:00.500 回答
0

在 Swift 3、Xcode 7.3 中验证

您也可以简单地PRINT查看每个上下文的内存引用并检查

(a) if the context exists,
(b) if the contexts of 2 objects are different

例如:(书和会员是2个不同的对象)

 print(book.managedObjectContext)
 print(member.managedObjectContext)

如果上下文存在但不同,它将打印这样的内容

0x7fe758c307d0
0x7fe758c15d70
于 2016-08-30T13:16:25.907 回答