iOS分享世界MG的Swift空间Swift开发指导

MG--Swift3.0简单使用CoreData

2017-01-10  本文已影响293人  Mg明明就是你


// MARK: - coreData
extension ViewController {
    /// 获取托管对象内容总管/也可以说是缓冲区(buff)
    func getContext () -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }
    
    /// 保存一条数据
    func storePerson(name:String, age: Int){
        let managerContext = getContext()
        // 定义一个entity,这个entity一定要在Xcdatamoded做好定义
        let entity = NSEntityDescription.entity(forEntityName: "Person", in: managerContext)
        
        let person = NSManagedObject(entity: entity!, insertInto: managerContext)
        person.setValue(name, forKey: "name")
        person.setValue(age, forKey: "age")
        
        peoples.append(person)
        try? managerContext.save()
    }
    
    /// 获取某一entity的所有数据
    func getPerson() -> [NSManagedObject]{
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        let searchResults = try? getContext().fetch(fetchRequest)
        print("numbers of \(searchResults!.count)")
        for p in (searchResults as! [NSManagedObject]){
            print("name:  \(p.value(forKey: "name")!) age: \(p.value(forKey: "age")!)")
        }
        return searchResults as! [NSManagedObject]
    }
}


//  ViewController.swift
//  coreData
//  Created by ming.com on 17/1/10.
//  Copyright © 2017年 ming. All rights reserved.

import UIKit
import CoreData
class ViewController: UIViewController {
    fileprivate lazy var tableView: UITableView = UITableView(frame: self.view.frame)
    var peoples = [NSManagedObject]()  // 数据源

    override func viewDidLoad() {
        super.viewDidLoad()
        // 1.把tableView加载到父控件当中
        tableView.dataSource = self
        view.addSubview(tableView)
        // 2.导航栏按钮添加和获取相关
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ViewController.addClick))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(ViewController.saveClick))
        // 3.获取数据
        peoples = getPerson()
    }
    
    @objc func addClick() {
        let alertVC = UIAlertController(title: "新建联系人", message: nil, preferredStyle: .alert)
        alertVC.addTextField { (textfield) in
            textfield.placeholder = "请输入名字"
        }
        alertVC.addTextField { (textfield) in
            textfield.placeholder = "请输入年龄"
            textfield.keyboardType = UIKeyboardType.numberPad
        }
        // 确定
        let sureAction = UIAlertAction(title: "确定", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            let text = alertVC.textFields?.first?.text
            let ageText = alertVC.textFields?.last?.text
            self.storePerson(name: text ?? "明明就是你", age: Int(ageText ?? "0")!)
            self.tableView.reloadData()
        })
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alertVC.addAction(sureAction)
        alertVC.addAction(cancelAction)
        present(alertVC, animated: true, completion: nil)
    }
        
    @objc func saveClick() {
        getPerson()
    }
}

// MARK: - coreData
extension ViewController {
    /// 获取托管对象内容总管
    func getContext () -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }
    
    /// 保存一条数据
    func storePerson(name:String, age: Int){
        let managerContext = getContext()
        // 定义一个entity,这个entity一定要在Xcdatamoded做好定义
        let entity = NSEntityDescription.entity(forEntityName: "Person", in: managerContext)
        
        let person = NSManagedObject(entity: entity!, insertInto: managerContext)
        person.setValue(name, forKey: "name")
        person.setValue(age, forKey: "age")
        
        peoples.append(person)
        try? managerContext.save()
    }
    
    /// 获取某一entity的所有数据
    func getPerson() -> [NSManagedObject]{
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        let searchResults = try? getContext().fetch(fetchRequest)
        print("numbers of \(searchResults!.count)")
        for p in (searchResults as! [NSManagedObject]){
            print("name:  \(p.value(forKey: "name")!) age: \(p.value(forKey: "age")!)")
        }
        return searchResults as! [NSManagedObject]
    }
}

// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peoples.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
        if cell == nil {
            cell = UITableViewCell(style: .value1, reuseIdentifier: "cellID")
        }
        let person = peoples[indexPath.row]
        cell?.textLabel?.text = person.value(forKey: "name") as? String
        cell?.detailTextLabel?.text = String(describing: person.value(forKey: "age")!)
        return cell!
    }
}







表的关联.png






//  CoreDataHelper.swift
//  coreData01
//  Created by i-Techsys.com on 17/1/15.
//  Copyright © 2017年 ming. All rights reserved.

import UIKit
import CoreData

class CoreDataHelper: NSObject {
    // MARK: - 便利构造方法
    var modelName: String = ""   // 数据库的名称 默认是App的名称
    override init() {
        super.init()
        var bundlePath = Bundle.main.bundlePath
        bundlePath = bundlePath.components(separatedBy: "/").last!
        bundlePath = bundlePath.components(separatedBy: ".").first!
        modelName = bundlePath
    }
    
    convenience init(modelName: String) {
        self.init()
        self.modelName = modelName
    }
    
    // 这个目录用来存放应用程序Core Data存储文件,在当前事例中,会在应用程序的Document目录下生成名为“FoodPin.Coredata”文件。
    // MARK: - Core Data stack
    @available(iOS 10.0 , *)
    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: self.modelName)
        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: self.modelName, withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()
    
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent(self.modelName + ".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 {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}



| 项目 | 简介 |
| : | : |
| MGDS_Swif | 逗视视频直播 |
| MGMiaoBo | 喵播视频直播 |
| MGDYZB | 斗鱼视频直播 |
| MGDemo | n多小功能合集 |
| MGBaisi | 高度仿写百思 |
| MGSinaWeibo | 高度仿写Sina |
| MGLoveFreshBeen | 一款电商App |
| MGWeChat | 小部分实现微信功能 |
| MGTrasitionPractice | 自定义转场练习 |
| DBFMDemo | 豆瓣电台 |
| MGPlayer | 一个播放视频的Demo |
| MGCollectionView | 环形图片排布以及花瓣形排布 |
| MGPuBuLiuDemo | 瀑布流--商品展 |
| MGSlideViewDemo | 一个简单点的侧滑效果,仿QQ侧滑 |
| MyResume | 一个展示自己个人简历的Demo |
| GoodBookDemo | 好书 |

Snip20161026_15.png
Snip20161026_16.png
Snip20161026_35.png 逗视介绍1.gif
逗视介绍2.gif
上一篇下一篇

猜你喜欢

热点阅读