2011-10-14 11 views
6

Estoy tratando de aprender a usar iCloud con datos del núcleo. Mi objetivo es sincronizar un único archivo de base de datos en mac/ios. Tanto mi Mac como iOS parecen estar actualizando iCloud, como puedo ver en Preferencias del Sistema-> iCloud-> Administrar ... Hay una aplicación llamada Desconocida que cada vez que cambio algo en la aplicación ios/mac se hace cada vez más grande. Eso me hace pensar que las aplicaciones están almacenando cambios en la nube. El problema es que no obtengo el NSPersistentStoreDidImportUbiquitousContentChangesNotification cuando cambio algo en la otra plataforma.No obtengo el NSPersistentStoreDidImportUbiquitousContentChangesNotification (con el ejemplo de código)

Ahí está mi código (aplicación 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; 
} 
+0

descubrí esos archivos están en la nube: ".baseline", ".cdmetadata.nosync", "kukosk.F8533032-7CA2-5A89-8097-62CD3D1C2FA3", "mobile.CB9C2446-D756- 575E-A553-7ABCFD2D369F " – Kukosk

Respuesta

1

que enfrentan el mismo problema con el SDK de iOS.

obtener notificaciones "NSPersistentStoreDidImportUbiquitousContentChangesNotification", debe llamar "- (void) addObserver: (id) selector de observador: nombre (SEL) aSelector: (NSString *) unNombre objeto: (id) unObjeto" de centro NSNotification.

I añade esta línea

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

en el método "didFinishLaunchingWithOptions" de AppDelegate. En mi caso, (iOS5) funcionó perfectamente, pero no sé si funcionará en mac os, también.

0

Estaba teniendo el mismo problema con la pila CoreData que se ejecuta en iOS y MacOS X. Entre mi iPhone y mi iPad, NSPersistentStoreDidImportUbiquitousContentChangesNotification: funcionó bien.

En Mac, terminé ejecutando periódicamente una NSFetchRequest (por ejemplo, cada 5 segundos) y descarté el resultado. Solo entonces llegó la notificación.

Cuestiones relacionadas