如何通过 AppDelegate 升级使功能可用于大于 8 的 iOS
Posted
技术标签:
【中文标题】如何通过 AppDelegate 升级使功能可用于大于 8 的 iOS【英文标题】:How to make functionality to be available for iOS greater than 8 with AppDelegate upgrade 【发布时间】:2016-10-01 19:22:18 【问题描述】:我从这里升级了我的 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)")
但是当我在视图控制器中编码时,我会在 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()
无论如何,我可以使用带有 swift 3 语法的 iOS 10,并为所有使用 iOS 8 及更高版本的设备提供功能。提前致谢
【问题讨论】:
【参考方案1】:是的,您可以针对 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)
您必须问自己的真正问题是,您为什么要先于客户采用 Core Data 功能?
【讨论】:
以上是关于如何通过 AppDelegate 升级使功能可用于大于 8 的 iOS的主要内容,如果未能解决你的问题,请参考以下文章