2017-02-22 54 views
0

我有一个应用程序,它使用支持ios 9以及ios 10的核心数据。我使用xcode 8.2.1开发此项目。 AppDelegate文件有方法来获取应用程序在ios 10上运行时的ManagedObjectContext,但是,如何在ios 9上运行应用程序时获取它。我尝试过谷歌,但没有任何帮助。任何帮助!ios 10和ios 9中的NSManagedObjectContext(核心数据)

我用它来获得ManagedObjectContext的代码是在这里:

NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext; 

回答

2

随着乔恩·罗斯提到,NSPersistentContainer只能从iOS的10 最好的解决办法,如果你仍然需要你的应用程序在以前的版本中的工作是用旧的核心数据堆栈,在这里你有一个很好的博客解释这两种方法之间的差异:Core Data in ios10

其他解决办法是使用#available属性,迅速执行核心数据堆栈或NSPersistentContainer,在这里你有关于这个文档:Swift Attributes

+0

嗨@Lucas我不熟悉swift的任何链接,如果你有这样的目标c的教程?以及任何方式感谢帮助 – kishan

+0

当然是的!在这里,您可以链接到Objective-C中的#available等价物:http://stackoverflow.com/questions/7848766/how-can-we-programmatically-detect-which-ios-version-is-device-running-on –

+0

不幸的是,在Objective-C中没有关于NSPersistentContainer的教程,在这里你有了文档,最好你可以按照swift中的教程并尝试用目标复制它。 https://developer.apple.com/reference/coredata/nspersistentcontainer?language=objc –

1

NSPersistentContainer只能从iOS的10及以后。如果你需要支持较低的系统,那么你不能使用它。您必须在不使用NSPersistentContainer的情况下设置自己的核心数据堆栈。

+0

任何帮助,我怎样才能执行这个,我已经尝试过o但是,它并没有帮助http://stackoverflow.com/questions/37956720/how-to-create-managedobjectcontext-using-swift-3-in-xcode-8 – kishan

+0

你可以试试https://github.com/inspace-IO/INSPersistentContainer。我看了一下代码,它并没有坏,但他没有写操作队列。 –

8

如果您的应用程序同时支持IOS 9以及IOS 10那么你可以使用#available属性来检查当前运行的版本并相应地运行代码,因为NSPersistentContainer仅适用于iOS 10及更高版本。

在斯威夫特3

// MARK: - Core Data Saving support 

    func saveContext() { 

     let coreDataFileName = "Use your core data file name" 

     if #available(iOS 10.0, *) { 
      let context = persistentContainer.viewContext 
      if context.hasChanges { 
       do { 
        try context.save() 
       } catch { 
        // Replace this implementation with code to handle the error appropriately. 
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        let nserror = error as NSError 
        fatalError("Unresolved error \(nserror), \(nserror.userInfo)") 
       } 
      } 
     }else { 

      if managedObjectContext.hasChanges { 
       do { 
        try managedObjectContext.save() 
       } catch let error as NSError { 
        print("Ops there was an error \(error.localizedDescription)") 
        abort() 
       } 
      } 

     } 
    } 

    // Applications default directory address 
    lazy var applicationDocumentsDirectory: NSURL = { 
     let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
     return urls[urls.count-1] as NSURL 
    }() 
    lazy var managedObjectModel: NSManagedObjectModel = { 
     // 1 
     let modelURL = Bundle.main.url(forResource: coreDataFileName, withExtension: "momd")! 
     return NSManagedObjectModel(contentsOf: modelURL)! 
    }() 
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { 
     let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
     let url = self.applicationDocumentsDirectory.appendingPathComponent("\(coreDataFileName).sqlite") 
     do { 
      // If your looking for any kind of migration then here is the time to pass it to the options 
      try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) 
     } catch let error as NSError { 
      print("Ops there was an error \(error.localizedDescription)") 
      abort() 
     } 
     return coordinator 
    }() 

    lazy var managedObjectContext: NSManagedObjectContext = { 
     // // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the 
     // application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to 
     // fail. 
     let coordinator = self.persistentStoreCoordinator 
     var context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) 
     context.persistentStoreCoordinator = coordinator 
     return context 
    }() 

在Objective - C 在AppDelegate.m

#pragma mark - Core Data Saving support 

@synthesize managedObjectContext = _managedObjectContext; 
@synthesize managedObjectModel = _managedObjectModel; 
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator; 
@synthesize persistentContainer = _persistentContainer; 

- (NSURL *)applicationDocumentsDirectory { 
    // The directory the application uses to store the Core Data store file. This code uses a directory named "Your Bundle Indentifier" in the application's documents directory. 
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
} 

- (NSManagedObjectModel *)managedObjectModel { 
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. 
    if (_managedObjectModel != nil) { 
     return _managedObjectModel; 
    } 
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Use your core data file name" withExtension:@"momd"]; 
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 
    return _managedObjectModel; 
} 

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. 
    if (_persistentStoreCoordinator != nil) { 
     return _persistentStoreCoordinator; 
    } 

    // Create the coordinator and store 

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Use your core data file name.sqlite"]; 
    NSError *error = nil; 
    NSString *failureReason = @"There was an error creating or loading the application's saved data."; 
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 
     // Report any error we got. 
     NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
     dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; 
     dict[NSLocalizedFailureReasonErrorKey] = failureReason; 
     dict[NSUnderlyingErrorKey] = error; 
     error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; 
     // Replace this with code to handle the error appropriately. 
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 

    return _persistentStoreCoordinator; 
} 


- (NSManagedObjectContext *)managedObjectContext { 
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) 
    if (_managedObjectContext != nil) { 
     return _managedObjectContext; 
    } 

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

#pragma mark - Core Data Saving support 

- (void)saveContext { 

    //Check current version. 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0){ 

     NSManagedObjectContext *context =_persistentContainer.viewContext; 

     if (context != nil) { 
      NSError *error = nil; 
      if ([context hasChanges] && ![context save:&error]) { 
       // Replace this implementation with code to handle the error appropriately. 
       // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
       NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
       abort(); 
      } 
     } 
    }else{ 
     NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 
     if (managedObjectContext != nil) { 
      NSError *error = nil; 
      if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 
       // Replace this implementation with code to handle the error appropriately. 
       // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
       NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
       abort(); 
      } 
     } 
    } 
} 

在AppDelegate.h使用

#pragma mark - Core data for messages vriable 
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext; 
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel; 
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator; 
@property (readonly, strong) NSPersistentContainer *persistentContainer; 

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

如果用户更新他的设备,该怎么办? –

+0

以上代码是从iOS 9及以上版本开始工作的 –