MG--Swift3.0简单使用CoreData
2017-01-10 本文已影响293人
Mg明明就是你
-
问题:什么时候使用CoreData?
- 数据模型之间关系比较简单的时候
-
如何简单使用CoreData
-
1.创建一个项目
- 勾选️Use Core Data. 如图所示
- 如图所示.png
- 勾选️Use Core Data. 如图所示
-
2.创建一个Person的表单
- 打开xcdatamodeld文件,新建一个entity,我们叫它Person,然后在右侧的Attributes里面增加属性,这里添加了name和age两个属性,type自选
- ![](http:https://img.haomeiwen.com/i1429890/bf9bfd577c1adb39.png?imageM
ogr2/auto-orient/strip%7CimageView2/2/w/1240) - 创建一个entity.png
-
- 调整实体属性
- ![](http:https://img.haomeiwen.com/i1429890/bf9bfd577c1adb39.png?imageM
- 打开xcdatamodeld文件,新建一个entity,我们叫它Person,然后在右侧的Attributes里面增加属性,这里添加了name和age两个属性,type自选
-
3.CoreData相关代码
- 获取托管对象内容总管/也可以说是缓冲区(buff)
- 保存一条数据
- 获取某一entity的所有数据
-
// 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
-
生成托管对象
- 生成托管对象
- 注意
-
获取数据的高级写法,通过代理进行数据的增删改查
- 高级获取数据
- NSFetchedResultsControllerDelegate代理方法
-
表的关联
表的关联.png
-
表的模糊和分页筛选
-
先来看看GIF效果
-
分页查询
- 分页查询.png
-
包含查询
- 包含查询.png
-
模糊查询
- 模糊查询.png
-
开头查询
- 开头查询.png
-
结尾查询
- 结尾查询.png
-
-
多表关联
-
打开CoreData的SQL语句输出开关
- 1.打开Product。点击EditScheme
- 2..点击Arguments,在ArgumentsPassed On Launch中添加两项
-com.apple.CoreData.SQLDebug
和1
,注意添加两项顺序不能颠倒。或者只添加一项-com.apple.CoreData.SQLDebug 1
打开CoreData的SQL输出开关如图演示png
-
-
不使用XCode自动生成的模板,可以自己创建工具类如下,用来多个数据库,一般一个数据库对应一个上下文Context
// 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)")
}
}
}
}
-
github
| 项目 | 简介 |
| : | : |
| MGDS_Swif | 逗视视频直播 |
| MGMiaoBo | 喵播视频直播 |
| MGDYZB | 斗鱼视频直播 |
| MGDemo | n多小功能合集 |
| MGBaisi | 高度仿写百思 |
| MGSinaWeibo | 高度仿写Sina |
| MGLoveFreshBeen | 一款电商App |
| MGWeChat | 小部分实现微信功能 |
| MGTrasitionPractice | 自定义转场练习 |
| DBFMDemo | 豆瓣电台 |
| MGPlayer | 一个播放视频的Demo |
| MGCollectionView | 环形图片排布以及花瓣形排布 |
| MGPuBuLiuDemo | 瀑布流--商品展 |
| MGSlideViewDemo | 一个简单点的侧滑效果,仿QQ侧滑 |
| MyResume | 一个展示自己个人简历的Demo |
| GoodBookDemo | 好书 |
Snip20161026_16.png
Snip20161026_35.png
-
2、逗视:逗你玩的直播App,可下载试玩
-
看下效果
逗视介绍2.gif