使用iCloud同步核心数据 - 排除实体

3
我正在为现有应用程序添加iCloud。同步工作正常,但是我需要排除一些实体,或想出一个解决方案,因为我的一些核心数据正在重复。例如:CertificateColour 发送到表视图,现在每行都显示两次。 CertificateType 在操作表中呈现四个选项,现在有8行存在,每行都被重复一次。我正在使用https://github.com/mluisbrown/iCloudCoreDataStack 进行核心数据同步。我查看了 Core data + iCloud: exclude certain attributes from sync? 它建议了几件事:
1. 创建单独的本地和云存储,听起来很有前途,但不确定如何进行,因为这是我第一次尝试使用 iCloud 和 Core Data。
2. 第二个建议是将同步到包含唯一设备标识符的实体,但已被弃用,同样不确定 Core Data 的处理过程。

AppDelegate.h

#import <UIKit/UIKit.h>
#import <sqlite3.h>
#import "PersistentStack.h"

@interface ICAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navigationController;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end

Appdelegate.m

@interface ICAppDelegate () <DBSessionDelegate, DBNetworkRequestDelegate>

//iCloud
@property (nonatomic, strong) PersistentStack* persistentStack;
@property (nonatomic, strong) NSManagedObjectContext* managedObjectContext;

@end

@implementation ICAppDelegate

@synthesize window = _window;
@synthesize navigationController = _navigationController;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //iCloud
    self.persistentStack = [[PersistentStack alloc] initWithStoreURL:self.storeURL modelURL:self.modelURL];
    self.managedObjectContext = self.persistentStack.managedObjectContext;



    BOOL populateData = NO;
    BOOL copyDb = YES;

    // Copy DB to documents directory
    if (copyDb == YES) {

        NSString *srcPath = [[NSBundle mainBundle] pathForResource:@"myApp" ofType:@"sqlite"];
        NSString *destPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"myApp.sqlite"];

        if (![[NSFileManager defaultManager] fileExistsAtPath:srcPath]) {
            DebugLog(@"Source file doesn't exist");
        }
        if (![[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
            DebugLog(@"Copying DB to documents directory");
            NSError *error = nil;
            [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:destPath error:&error];
            if (error != nil) {
                DebugLog(@"Copy failed %@", [error localizedDescription]);
            }
        }
    }


    /////*****ALL OF THIS IS DUPLICATED AND NEEDS EXCLUDING FROM ICLOUD BACK UP****////////////

        if (populateData) {

        DebugLog(@"Populating database");
        NSManagedObjectContext *context = [self managedObjectContext];

        Subscription *subscription = (Subscription *)[NSEntityDescription insertNewObjectForEntityForName:@"Subscription" inManagedObjectContext:context];
        subscription.subscribed = @NO;

        CertificateColour *red = (CertificateColour *)[NSEntityDescription insertNewObjectForEntityForName:@"CertificateColour" inManagedObjectContext:context];
        red.name = @"Red";
        red.redComponent = @1.0f;
        red.greenComponent = @0.0f;
        red.blueComponent = @0.0f;

        CertificateColour *purple = (CertificateColour *)[NSEntityDescription insertNewObjectForEntityForName:@"CertificateColour" inManagedObjectContext:context];
        purple.name = @"Purple";
        purple.redComponent = @0.4f;
        purple.greenComponent = @0.0f;
        purple.blueComponent = @0.6f;

        CertificateColour *green = (CertificateColour *)[NSEntityDescription insertNewObjectForEntityForName:@"CertificateColour" inManagedObjectContext:context];
        green.name = @"Green";
        green.redComponent = @0.0f;
        green.greenComponent = @0.6f;
        green.blueComponent = @0.2f;

        CertificateColour *blue = (CertificateColour *)[NSEntityDescription insertNewObjectForEntityForName:@"CertificateColour" inManagedObjectContext:context];
        blue.name = @"Blue";
        blue.redComponent = @0.0f;
        blue.greenComponent = @0.2f;
        blue.blueComponent = @1.0f;


        ICCertificateTypeManager *ctm = [ICCertificateTypeManager manager];

        CertificateType *type = [ctm newCertificateType];
        type.title = @"Works";
        type.identifier = @(Works);

        type = [ctm newCertificateType];
        type.title = @"Type1";
        type.identifier = @(Type1);

        type = [ctm newCertificateType];
        type.title = @"Type2";
        type.identifier = @(Type2);

        type = [ctm newCertificateType];
        type.title = @"Type4";
        type.identifier = @(Type3);

        [self saveContext];
    }

       if ([[ICWebServiceClient sharedInstance] isLoggedIn])
    {
        DebugLog(@"User is logged in ");
    }
    ////////////////////////////////////////////////////////////


    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    LogCmd();
    if ([[DBSession sharedSession] handleOpenURL:url]) {
        if ([[DBSession sharedSession] isLinked]) {
            DebugLog(@"handling url");
        }
        return YES;
    }

    return NO;
}

- (void)applicationWillResignActive:(UIApplication *)application
{

}

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    [self.managedObjectContext save:NULL];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{

}

- (void)applicationDidBecomeActive:(UIApplication *)application
{

}

- (void)applicationWillTerminate:(UIApplication *)application
{

    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {


            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}


#pragma mark - DBSessionDelegate

- (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
{
    LogCmd();
}

#pragma mark - DBNetworkRequestDelegate

static int outstandingRequests;

- (void)networkRequestStarted {
    outstandingRequests++;
    if (outstandingRequests == 1) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    }
}

- (void)networkRequestStopped {
    outstandingRequests--;
    if (outstandingRequests == 0) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }
}


#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil) {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"myApp" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil) {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"myApp.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {





        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    

    return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


#pragma mark - iCloud store

- (NSURL*)storeURL
{
    NSURL* documentsDirectory = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];
    return [documentsDirectory URLByAppendingPathComponent:@"myApp.sqlite"];
}

- (NSURL*)modelURL
{
    return [[NSBundle mainBundle] URLForResource:@"myApp" withExtension:@"momd"];
}


@end
1个回答

4
使用多个持久存储库确实是排除特定实体类型不在iCloud中的唯一选择。您可以通过在同一持久性存储协调器上调用addPersistentStoreWithType多次,但使用不同的持久性存储文件来实现(它被称为协调器,因为它可以在多个持久性存储之间协调)。对其中一个存储使用iCloud选项,但对另一个存储不要使用。
您可以使用具有不同实体的两个单独的托管对象模型,也可以使用具有不同配置选项的单个模型。任何一种方法都是有效的。
您可能会遇到的问题是无法在不同的持久性存储文件之间创建实例之间的关系。(从技术上讲,您可以创建它们,只是不能保存它们,在大多数情况下使它们无用)。您的CertificateType实体似乎需要与其他实例建立关系,但这在多个存储中不起作用。
相反,您可以同步每个对象,但添加代码以检测重复项并处理它们。在WWDC 2012年的“使用Core Data与iCloud”会话中,苹果公司的“SharedCoreData”示例应用程序中有一个很好的例子,但我现在找不到在线副本。您可以这样做:
1.等待NSPersistentStoreDidImportUbiquitousContentChangesNotification 2.当它到达时,查看通知的userInfo以查看是否包括任何CertificateType对象。
3.如果是,则为该实体执行获取操作以查找并匹配重复项
4.以适合您的应用程序的方式清除这些重复项。 更新:我忘记了我在博客文章中更详细地涵盖了此内容。我还找到了一个链接到WWDC 2012示例代码包(链接需要当前开发人员帐户),其中包括SharedCoreData。该演示中的许多内容已经过时,但删除重复项的代码仍然有效。

谢谢Tom,我会查看你的博客文章和示例代码,感谢提供链接,谢谢。 - JSA986
我已经反复阅读了你的博客文章,尝试将“- (void)deDupe:(NSNotification *)importNotification {”实现到我的代码中,但是我仍然没有进展。难道没有更简单的方法吗?有一篇帖子提到创建单独的本地和云存储? - JSA986
我不知道更简单的方法。你需要找到重复项并处理它们,我也不知道更好的方法。使用单独的云和本地堆栈对此并没有任何影响。 - Tom Harrington

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接