Я не получаю NSPersistentStoreDidImportUbiquitousContentChangesNotification (с примером кода)

#cocoa #core-data #xcode4.2 #icloud

#cocoa #основные данные #xcode4.2 #icloud

Вопрос:

Я пытаюсь научиться использовать iCloud с coredata. Моя цель — синхронизировать один файл базы данных на mac / ios. Похоже, что мои приложения для Mac и iOS обновляют iCloud, поскольку я вижу это в разделе «Системные настройки» -> «iCloud» -> «Управление» … Есть приложение с именем Unknown, которое каждый раз, когда я что-то меняю в приложении ios / Mac, становится все больше и больше. Это заставляет меня думать, что приложения сохраняют изменения в облаке. Проблема в том, что я не получаю NSPersistentStoreDidImportUbiquitousContentChangesNotification , когда я что-то меняю на другой платформе.

Вот мой код (приложение для Mac):

 - (void)persistentStoreDidImportUbiquitousContentChangesNotification:(NSNotification *)notif
{
    NSLog(@"%@", notif);
}

- (NSURL *)applicationFilesDirectory
{
    NSString *identifier = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *libraryURL = [[[fileManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:identifier];

    if(![fileManager fileExistsAtPath:[libraryURL path]])
    {
        [fileManager createDirectoryAtPath:[libraryURL path] withIntermediateDirectories:YES attributes:nil error:nil];
    }

    return libraryURL;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel)
    {
        return __managedObjectModel;
    }

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyApp" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
    return __managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator)
    {
        return __persistentStoreCoordinator;
    }

    NSManagedObjectModel *mom = [self managedObjectModel];
    if (!mom)
    {
        NSLog(@"%@:%@ No model to generate a store from", [self class], NSStringFromSelector(_cmd));
        return nil;
    }

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *applicationFilesDirectory = [self applicationFilesDirectory];
    NSError *error = nil;

    NSDictionary *properties = [applicationFilesDirectory resourceValuesForKeys:[NSArray arrayWithObject:NSURLIsDirectoryKey] error:amp;error];

    if (!properties)
    {
        BOOL ok = NO;
        if ([error code] == NSFileReadNoSuchFileError)
        {
            ok = [fileManager createDirectoryAtPath:[applicationFilesDirectory path] withIntermediateDirectories:YES attributes:nil error:amp;error];
        }
        if (!ok)
        {
            [[NSApplication sharedApplication] presentError:error];
            return nil;
        }
    }
    else
    {
        if ([[properties objectForKey:NSURLIsDirectoryKey] boolValue] != YES)
        {
            NSString *failureDescription = [NSString stringWithFormat:@"Expected a folder to store application data, found a file (%@).", [applicationFilesDirectory path]]; 

            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            [dict setValue:failureDescription forKey:NSLocalizedDescriptionKey];
            error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:101 userInfo:dict];

            [[NSApplication sharedApplication] presentError:error];
            return nil;
        }
    }

    NSString *appBundleID = [[NSBundle mainBundle] bundleIdentifier];
    NSURL *storeURL = [applicationFilesDirectory URLByAppendingPathComponent:@"MyApp.sqlite"];
    NSURL *cloudURL = [[fileManager URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:@"Database"];

    NSPersistentStoreCoordinator *coordinator = [[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom] autorelease];
    NSDictionary *optionsDict = [NSDictionary dictionaryWithObjectsAndKeys:appBundleID, NSPersistentStoreUbiquitousContentNameKey, cloudURL, NSPersistentStoreUbiquitousContentURLKey, [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,nil];
    if (![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:optionsDict error:amp;error])
    {
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }
    __persistentStoreCoordinator = [coordinator retain];

    return __persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext)
    {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator)
    {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
        [dict setValue:@"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
        NSError *error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        [[NSApplication sharedApplication] presentError:error];
        return nil;
    }
    __managedObjectContext = [[NSManagedObjectContext alloc] init];
    [__managedObjectContext setPersistentStoreCoordinator:coordinator];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(persistentStoreDidImportUbiquitousContentChangesNotification:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];

    return __managedObjectContext;
}
  

Комментарии:

1. Я обнаружил, что эти файлы находятся в облаке: «.baseline», «.cdmetadata.nosync», «kukosk.F8533032-7CA2-5A89-8097-62CD3D1C2FA3», «мобильный. CB9C2446-D756-575E-A553-7ABCFD2D369F»

Ответ №1:

Я столкнулся с той же проблемой с iOS SDK.

Чтобы получить уведомление «NSPersistentStoreDidImportUbiquitousContentChangesNotification», вы должны вызвать «- (void) addObserver: (id) селектор наблюдателя: (SEL) Имя селектора:(NSString *) Объект aName:(id) anObject» из центра NSNotification.

Я добавил эту строку

[[NSNotificationCenter defaultCenter] addObserver:masterViewController selector:@selector(notifyiCloud:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:[self persistentStoreCoordinator]];

в методе AppDelegate «didFinishLaunchingWithOptions». В моем случае (iOS5) он работал отлично, но я не знаю, будет ли он работать и в Mac os.

Ответ №2:

У меня была такая же проблема со стеком CoreData, работающим как на iOS, так и на macOS X. Между моим iPhone и iPad NSPersistentStoreDidImportUbiquitousContentChangesNotification: s работал нормально.

На Mac я закончил тем, что периодически выполнял NSFetchRequest (скажем, каждые 5 секунд) и отбрасывал результат. Только тогда пришло уведомление.