如何在iCloud同步后从NSNotification获取NSManagedObject

时间:2014-05-30 15:25:19

标签: objective-c icloud

我需要根据在iCloud NSPersistentStoreDidImportUbiquitousContentChangesNotification中插入/更新NSManagedObject的时间来运行更新。我需要从NSManagedObject获取一个名为“url”的更新/插入的属性。这是我到目前为止的代码......

//called when there is a change to iCloud data
- (void)cloudChanges:(NSNotification*)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSDictionary *info = notification.userInfo;
    NSSet *insertedObjects = [info objectForKey:NSInsertedObjectsKey];
    NSSet *updatedObjects = [info objectForKey:NSUpdatedObjectsKey];
    NSSet *deletedObjects = [info objectForKey:NSDeletedObjectsKey];

    /*this is where i need to loop thru the objects and do something
    based on the url attribute of the NSManagedObject, the classname is ItemMeta
    */
    for (NSManagedObject *object in updatedObjects) {
        if ([[object entity].name isEqualToString:@"ItemMeta"]) {         
           // NSDictionary *entityDic = [object entity];
            //NSDictionary *changesDic = [object changedValues];
            //NSLog(@"changesDic.url: %@", [changesDic objectForKey:@"url"]);

            ItemMeta *itemMeta = (ItemMeta *)[object entity];
           //this line throws an error "unrecognized selector sent to instance"
            NSArray *itemMetas = [self getAllItemMetadataForURL:itemMeta.url];

        }
    }

***这里是正确迭代NSUpdatedObjectsKey 2014年6月6日的更新

     for (NSManagedObjectID *objectID in updatedObjects) {
            NSManagedObject *object = [self.mocMaster objectWithID:objectID];
            if ([object isKindOfClass:[ItemMeta class]]) {
                ItemMeta *itemMeta = (ItemMeta *)object;
                NSArray *itemMetas = [self getAllItemMetadataForURL:itemMeta.url];
            }
        }

*** 2014年6月6日更新结束

    [self.mocMaster mergeChangesFromContextDidSaveNotification:notification];

}

1 个答案:

答案 0 :(得分:0)

您并没有真正提出问题或说出您的代码存在什么问题。尽管如此:

ItemMeta *itemMeta = (ItemMeta *)[object entity];

真的应该是:

<击> ItemMeta *itemMeta = (ItemMeta *)object;

ItemMeta *itemMeta = (ItemMeta*)[self.mocMaster objectWithID:object]

entity更多是类描述,而不是对象实例。 object是您需要强制转换为实体类类型的对象实例。 object原来是iCloud通知的NSManagedObjectID

你也可以使用[object isKindOfClass:[ItemMeta class]] - 没有机会在字符串文字中输入拼写错误。

您也应该首先执行mergeChange,以便获得更新的对象。