代码之家  ›  专栏  ›  技术社区  ›  Coder221

如何通过AppDelegate升级使功能可用于大于8的iOS

  •  1
  • Coder221  · 技术社区  · 8 年前

    我从此升级了我的AppDelegate

    // MARK: - Core Data stack
    
        lazy var applicationDocumentsDirectory: URL = {
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            return urls[urls.count-1]
        }()
    
        lazy var managedObjectModel: NSManagedObjectModel = {
            let modelURL = Bundle.main.url(forResource: "TestProject", withExtension: "momd")!
            return NSManagedObjectModel(contentsOf: modelURL)!
        }()
    
        lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    
            // Create the coordinator and store
            let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
            let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
            var failureReason = "There was an error creating or loading the application's saved data."
            do {
                try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
            } catch {
                // Report any error we got.
                var dict = [String: AnyObject]()
                dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
                dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
    
                dict[NSUnderlyingErrorKey] = error as NSError
                let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
    
                NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
                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 managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
            managedObjectContext.persistentStoreCoordinator = coordinator
            return managedObjectContext
        }()
    
        // MARK: - Core Data Saving support
    
        func saveContext () {
            if managedObjectContext.hasChanges {
                do {
                    try managedObjectContext.save()
                } catch {
                    // 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.
                    let nserror = error as NSError
                    NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                    abort()
                }
            }
        }
    

    这样我就可以使用iOS 10用Swift 3编码核心数据

    // MARK: - Core Data stack
    
        @available(iOS 10.0, *)
        lazy var persistentContainer: NSPersistentContainer = {
    
            let container = NSPersistentContainer(name: "TestProject")
            container.loadPersistentStores(completionHandler: { (storeDescription, error) in
                if let error = error as NSError? {
    
                    fatalError("Unresolved error \(error), \(error.userInfo)")
                }
            })
            return container
        }()
    
        // MARK: - Core Data Saving support
    
        @available(iOS 10.0, *)
        func saveContext () {
            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)")
                }
            }
        }
    

    但当我在view controller中编码时,我可以在iOS 10.0上使用这些

    @IBAction func saveBtnPressed(_ sender: AnyObject) {
    
            if #available(iOS 10.0, *) {
                let context =   (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
                let task = Task(context: context)
                task.taskDesc = goalText.text!
                task.taskImage = UIImagePNGRepresentation(choosenImage!)! as NSData?
    
            } else {
                // Fallback on earlier versions
            }
            //Save the data to coredata
            (UIApplication.shared.delegate as! AppDelegate).saveContext()
        }
    

    无论如何,我可以使用iOS 10和swift 3语法,并为所有使用iOS 8及以上的设备提供功能。提前感谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   adonoho    8 年前

    是的,您可以针对iOSv8发布Swift 3代码。下面是一个使用Swift v2.3的示例(v2.3与v3.0对于框架功能检测来说是一个不重要的区别):

    convenience init(moc: NSManagedObjectContext) {
        if #available(iOS 10.0, *) {
            self.init(context: moc)
        }
        else {
            let name = NSStringFromClass(self.dynamicType)
            let entityName = name.componentsSeparatedByString(".").last!
            let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: moc)!
            self.init(entity: entity, insertIntoManagedObjectContext: moc)
        }
    }
    

    您必须问自己的真正问题是,为什么您要在客户之前接受核心数据功能?