【问题标题】:Xcode 8 auto generated Core Data stack is not supported with iOS 9 and belowiOS 9 及更低版本不支持 Xcode 8 自动生成的 Core Data 堆栈
【发布时间】:2017-02-22 17:10:11
【问题描述】:

标题解释了确切的问题。基本 CoreData 主详细信息模板仅适用于 iOS 10 及更高版本。但是如果你尝试在 iOS 9 或更低版本上运行相同的模板,它会崩溃,因为 persistentContainer 没有创建,我们曾经得到 NSManagedObjectContext。这是由于最新的 iOS 10 添加了 xCode 8。我看到 Swift 的解决方法很少,但 Objective-C 却没有。 Objc 有更好的解决方案吗?

【问题讨论】:

    标签: ios core-data xcode8


    【解决方案1】:

    这是解决方案,

    由于iOS 9及以上没有persistentContainer基础设施,基本上你必须像这样自己初始化核心数据栈,

    将此方法放在您的委托类中的任何位置,这是我们在 iOS 10 persistentContainer 介绍之前一直在做的事情。

    - (void)initializeCoreData
    {
    
        NSDictionary *options = @{ NSSQLitePragmasOption : @{@"journal_mode" : @"DELETE"}};
    
        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"yourmodelname" withExtension:@"momd"];
        NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
        NSAssert(mom != nil, @"Error initializing Managed Object Model");
    
        NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
        NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [moc setPersistentStoreCoordinator:psc];
        _managedObjectContext = moc;
        [EFLDatabase sharedDatabaseWithManagedObjectContext:_managedObjectContext];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *documentsURL = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
        NSLog(@"DOC %@", [documentsURL absoluteString]);
        NSURL *storeURL = [documentsURL URLByAppendingPathComponent:@"yourmodelname.sqlite"];
    
        dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
            NSError *error = nil;
            NSPersistentStoreCoordinator *psc = [[self managedObjectContext] persistentStoreCoordinator];
            NSPersistentStore *store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];
            NSAssert(store != nil, @"Error initializing PSC: %@\n%@", [error localizedDescription], [error userInfo]);
        });
    }
    

    现在把sn-p下面放到didFinishLaunchingWithOptions方法里面,基本会检查iOS版本低于10,然后执行上面的方法,

    if ([[NSProcessInfo processInfo] operatingSystemVersion].majorVersion < 10) {
            [self initializeCoreData];
    }
    

    【讨论】:

      【解决方案2】:

      下载 Xcode 7,从模板创建一个项目并检查 use core data,然后从 App Delegate 复制 Core Data 堆栈

      【讨论】:

      • 感谢您的回复。我已经尝试过了,但不幸的是它对我不起作用。
      • 当你说“它对我不起作用”时,究竟是什么问题?
      • 好吧,它并没有自动调用managedObjectContext 方法来继续创建上下文。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      相关资源
      最近更新 更多