Swift 3.0 使用CoreData兼容iOS9和iOS10的CoreData實例

寫在前面,由于蘋果公司對CoreData的改動,使得在Xcode8.0和ios10.0以上環(huán)境下使用新語法使用CoreData不兼容ios9以下系統(tǒng)赋续,本實例主要簡單介紹Swift3.0中CoreData的使用,同時處理了不兼容ios9以下版本系統(tǒng)的問題玄渗。

開發(fā)環(huán)境:Xcode8.1粱檀,iOS10.0

說明:本實例為swift純代碼編寫

下面為實例的主要實現(xiàn)代碼:

AppDelegate.swift

import UIKit  
import CoreData 
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
   var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //創(chuàng)建導航視圖為主界面
    window = UIWindow(frame:UIScreen.main.bounds);
    window?.backgroundColor = UIColor.white;
    let nav = UINavigationController(rootViewController: ViewController());
    window?.rootViewController = nav;
    window?.makeKeyAndVisible();
    return true
}

 //省略......

func applicationWillTerminate(_ application: UIApplication) {
    if #available(iOS 10.0, *) {
        self.saveContext()
    } else {
    }
}

// MARK: - Core Data stack
@available(iOS 10.0 , *)
lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "saveDataDemo")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

lazy var applicationDocumentsDirectory: URL = {
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return urls[urls.count-1]
}()
//iOS9下的 Core Data stack
lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = Bundle.main.url(forResource: "saveDataDemo", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    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 = {
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()
  //iOS9下的 Core Data stack結束
// 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)")
        }
    }
}

}

ViewController.swift

import UIKit
import CoreData
class ViewController: UIViewController , UITextFieldDelegate{
var mycontext : NSManagedObjectContext!;
var  mynum , myname , myage : UITextField!;

override func viewDidLoad() {
    if #available(iOS 10.0, *) {
        mycontext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
    } else {
        print("IOS9");
        mycontext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
    }
    super.viewDidLoad()
   
   //此處省略界面創(chuàng)建代碼詳細請看源文件
    //添加事件實現(xiàn)隱藏鍵盤
    let tap = UITapGestureRecognizer(target: self, action: #selector(tap(G:)));
    self.view.addGestureRecognizer(tap);
}
//界面跳轉
func showData(){
    navigationController?.pushViewController(showViewController(), animated: true);
}

//隱藏鍵盤
func tap(G:UITapGestureRecognizer) {
    self.view.endEditing(true);
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    self.view.endEditing(true);
    return true;
}

//保存數(shù)據(jù)到CoreData
func SavaDataToCoredata(){
    do{
        let inserInfo = NSEntityDescription.insertNewObject(forEntityName: "MyStudents", into: mycontext);
        if(mynum.text != "" && myname.text != "" && myage.text != ""){
            inserInfo.setValue(Int(mynum.text!), forKey: "num");
            inserInfo.setValue("\(myname.text!)", forKey: "name");
            inserInfo.setValue(Int(myage.text!), forKey: "age");
            try mycontext.save()
            mynum.text = "";
            myname.text = "";
            myage.text = "";
            let myAlert = UIAlertController(title: "提示", message: "保存成功", preferredStyle: .alert);
            let myokAction = UIAlertAction(title: "確定", style: .default, handler: nil);
            myAlert.addAction(myokAction);
            self.present(myAlert, animated: true, completion: nil);
            
        }else{
            let myAlert = UIAlertController(title: "提示", message: "請輸入完整的信息", preferredStyle: .alert);
            let myOkAction = UIAlertAction(title: "確定", style: .default, handler: nil);
            myAlert.addAction(myOkAction);
            self.present(myAlert, animated: true, completion: nil);
            
        }
        
    }catch{
        fatalError();
    }
}
//清除coreData中的數(shù)據(jù)
func delCoreData(){
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MyStudents");
    do{
        let rels = try mycontext.fetch(request) as! [NSManagedObject];
        for rel in rels{
            mycontext.delete(rel);
        }
        try mycontext.save();
        let myAlert = UIAlertController(title: "提示", message: "清空數(shù)據(jù)庫成功", preferredStyle: .alert);
        let myOkAction = UIAlertAction(title: "確定", style: .default, handler: nil);
        myAlert.addAction(myOkAction);
        present(myAlert, animated: true, completion: nil);
    }catch{
        fatalError();
    }
    
}

}

showViewController.swift

import UIKit;
import CoreData;
class showViewController: UIViewController {
let fullsize = UIScreen.main.bounds.size;
let myEntity = "Students";
var myContext : NSManagedObjectContext!;
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MyStudents");
var myTextView : UITextView!;
override func viewDidLoad() {
    if #available(iOS 10.0, *) {
        myContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
    } else {
        myContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
    }
    super.viewDidLoad()

    self.title = "顯示數(shù)據(jù)";
    self.view.backgroundColor = UIColor.white;
    
    myTextView = UITextView(frame: CGRect(x: 0, y: 0, width: fullsize.width, height: fullsize.height));
    myTextView.center = CGPoint(x: fullsize.width * 0.5, y: fullsize.height * 0.5);
    myTextView.textAlignment = .left;
    myTextView.textColor = UIColor.red;
    myTextView.isEditable = false;
    self.view.addSubview(myTextView);
    show();
}

func show(){
    do{
        let rels = try myContext.fetch(request) as! [NSManagedObject];
        var re = "";
        for rel in rels {
            if rel.value(forKey: "name") != nil{
                re += "\n學號:000\(rel.value(forKey: "num")!)\n" + "姓名: \(rel.value(forKey: "name")!)\n" + "年齡: \(rel.value(forKey: "age")!)\n";
            }
        }
        if re != ""{
            myTextView.text = re;
        }else{
            myTextView.text = "未找到相關數(shù)據(jù)!";
            myTextView.textColor = UIColor.red;
        }
    }catch{
        fatalError();
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

下面是程序運行效果圖

未命名.png

源碼地址:https://github.com/pkx0128/saveDataDemo.git

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末败玉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子镜硕,更是在濱河造成了極大的恐慌运翼,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,080評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件兴枯,死亡現(xiàn)場離奇詭異血淌,居然都是意外死亡,警方通過查閱死者的電腦和手機念恍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,422評論 3 385
  • 文/潘曉璐 我一進店門六剥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來晚顷,“玉大人峰伙,你說我怎么就攤上這事「媚” “怎么了瞳氓?”我有些...
    開封第一講書人閱讀 157,630評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長栓袖。 經(jīng)常有香客問我匣摘,道長,這世上最難降的妖魔是什么裹刮? 我笑而不...
    開封第一講書人閱讀 56,554評論 1 284
  • 正文 為了忘掉前任音榜,我火速辦了婚禮,結果婚禮上捧弃,老公的妹妹穿的比我還像新娘赠叼。我一直安慰自己,他們只是感情好违霞,可當我...
    茶點故事閱讀 65,662評論 6 386
  • 文/花漫 我一把揭開白布嘴办。 她就那樣靜靜地躺著,像睡著了一般买鸽。 火紅的嫁衣襯著肌膚如雪涧郊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,856評論 1 290
  • 那天眼五,我揣著相機與錄音妆艘,去河邊找鬼彤灶。 笑死,一個胖子當著我的面吹牛批旺,可吹牛的內容都是我干的枢希。 我是一名探鬼主播,決...
    沈念sama閱讀 39,014評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼朱沃,長吁一口氣:“原來是場噩夢啊……” “哼苞轿!你這毒婦竟也來了?” 一聲冷哼從身側響起逗物,我...
    開封第一講書人閱讀 37,752評論 0 268
  • 序言:老撾萬榮一對情侶失蹤搬卒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后翎卓,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體契邀,經(jīng)...
    沈念sama閱讀 44,212評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,541評論 2 327
  • 正文 我和宋清朗相戀三年失暴,在試婚紗的時候發(fā)現(xiàn)自己被綠了坯门。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,687評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡逗扒,死狀恐怖古戴,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情矩肩,我是刑警寧澤现恼,帶...
    沈念sama閱讀 34,347評論 4 331
  • 正文 年R本政府宣布,位于F島的核電站黍檩,受9級特大地震影響叉袍,放射性物質發(fā)生泄漏。R本人自食惡果不足惜刽酱,卻給世界環(huán)境...
    茶點故事閱讀 39,973評論 3 315
  • 文/蒙蒙 一喳逛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧棵里,春花似錦润文、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,777評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至稳捆,卻和暖如春赠法,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,006評論 1 266
  • 我被黑心中介騙來泰國打工砖织, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留款侵,地道東北人。 一個月前我還...
    沈念sama閱讀 46,406評論 2 360
  • 正文 我出身青樓侧纯,卻偏偏與公主長得像新锈,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子眶熬,可洞房花燭夜當晚...
    茶點故事閱讀 43,576評論 2 349

推薦閱讀更多精彩內容