在TodayExtension中使用MagicalRecord(CoreData)

时间:2016-01-30 13:25:14

标签: ios objective-c core-data magicalrecord

我正在为任务列表的生产力应用程序开发TodayExtension,我需要在TodayExtension中的表格中显示一些任务的列表。

设置表格视图时没有任何问题,但是当我尝试设置MagicalRecord和CoreData时,我遇到了崩溃。

我崩溃的方法的源代码是:

- (void)setupCoreDataStackWithStoreNamed:(NSString *)storeNamed
{
    if ([NSPersistentStoreCoordinator MR_defaultStoreCoordinator] != nil)
    {
        return;
    }

    NSManagedObjectModel *model = [NSManagedObjectModel MR_defaultManagedObjectModel];
    NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

    NSString *containerPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP].path;
    NSString *sqlitePath = [NSString stringWithFormat:@"%@/%@", containerPath, storeNamed];
    NSURL *storeURL = [NSURL URLWithString:sqlitePath];

    [psc MR_addSqliteStoreNamed:storeURL withOptions:nil];
    [NSPersistentStoreCoordinator MR_setDefaultStoreCoordinator:psc];
    [NSManagedObjectContext MR_initializeDefaultContextWithCoordinator:psc];
}

崩溃的路线是:

    [psc MR_addSqliteStoreNamed:storeURL withOptions:nil];

错误消息是:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'CoreData SQL stores only support file URLs (got /private/var/mobile/Containers/Shared/AppGroup/66A40F3A-9E25-42BD-9BD0-D86BC5A93FBD/myappname_560967e1665e88ab37000000.sqlite).'

我从这篇文章获得灵感How to access CoreData model in today extension (iOS)

1 个答案:

答案 0 :(得分:1)

您正在将NSString网址(/ .. / ...)传递给MR_addSqliteStoreNAamed,但崩溃告诉您需要传递文件网址(file:// .. 。)

所以你必须改变这个源代码:

NSString *containerPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP].path;
NSString *sqlitePath = [NSString stringWithFormat:@"%@/%@", containerPath, storeNamed];
NSURL *storeURL = [NSURL URLWithString:sqlitePath];

到此:

NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:APP_GROUP];
storeURL = [storeURL URLByAppendingPathComponent:storeNamed];

另一种解决方案可能是:

NSString *pathToYourSqliteFile = @"/your/path/here";
NSURL *storeURL = [NSURL fileURLWithPath: isDirectory:NO];