我没有得到NSPersistentStoreDidImportUbiquitousContentChangesNotification(带代码示例)

Kuk*_*osk 6 cocoa core-data icloud xcode4.2

我正在尝试学习如何将iCloud与coredata一起使用.我的目标是在mac/ios上同步一个数据库文件.我的mac和iOS应用程序似乎都在更新iCloud,因为我可以在系统偏好设置 - > iCloud-> Manage ...下看到它有一个名为Unknown的应用程序,每次我在ios/mac应用程序上更改内容越来越大.这让我觉得应用程序正在存储对云的更改.问题是,我没有得到NSPersistentStoreDidImportUbiquitousContentChangesNotification我在其他平台上改变某些东西的时间.

有我的代码(mac app):

- (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:&error];

    if (!properties)
    {
        BOOL ok = NO;
        if ([error code] == NSFileReadNoSuchFileError)
        {
            ok = [fileManager createDirectoryAtPath:[applicationFilesDirectory path] withIntermediateDirectories:YES attributes:nil error:&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:&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;
}
Run Code Online (Sandbox Code Playgroud)

小智 1

我在使用 iOS SDK 时也遇到了同样的问题。

要获取“NSPersistentStoreDidImportUbiquitousContentChangesNotification”通知,您必须从 NSNotification 中心调用“- (void)addObserver:(id)observer 选择器:(SEL)aSelector name:(NSString *)aName object:(id)anObject”。

我添加了这一行

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

在 AppDelegate 的“didFinishLaunchingWithOptions”方法中。就我而言,(iOS5)它运行得很好,但我不知道它是否也能在 mac os 中运行。