6

コアデータでiCloudを使用する方法を学ぼうとしています。私の目標は、mac/ios で単一のデータベース ファイルを同期することです。システム環境設定-> iCloud->管理で確認できるように、私のMacアプリとiOSアプリの両方がiCloudを更新しているようです... ios / macアプリで何かを変更するたびに、Unknownという名前のアプリがどんどん大きくなっています。つまり、アプリが変更をクラウドに保存していると思います。問題は、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:&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;
}
4

2 に答える 2

1

iOSSDKでも同じ問題に直面しました。

「NSPersistentStoreDidImportUbiquitousContentChangesNotification」通知を取得するには、NSNotificationセンターから「-(void)addObserver:(id)observerselector:(SEL)aSelector name:(NSString *)aNameobject:(id)anObject」を呼び出す必要があります。

この行を追加しました

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

AppDelegateの「didFinishLaunchingWithOptions」メソッドで。私の場合、(iOS5)は完全に機能しましたが、macosでも機能するかどうかはわかりません。

于 2011-10-16T01:53:08.670 に答える
0

iOSとMacOSXの両方で実行されているCoreDataスタックで同じ問題が発生していました。iPhoneとiPadの間で、NSPersistentStoreDidImportUbiquitousContentChangesNotification:sは正常に機能しました。

Macでは、NSFetchRequestを定期的に(たとえば5秒ごとに)実行し、結果を破棄することになりました。その後、通知が届きました。

于 2012-11-01T15:54:28.813 に答える