欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS CoreData 增刪改查詳解

 更新時(shí)間:2016年09月19日 09:31:20   作者:肖品  
這篇文章主要為大家詳細(xì)介紹了iOS CoreData 增刪改查的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

最近在學(xué)習(xí)CoreData, 因?yàn)轫?xiàng)目開發(fā)中需要,特意學(xué)習(xí)和整理了一下,整理出來方便以后使用和同行借鑒。目前開發(fā)使用的Swift語言開發(fā)的項(xiàng)目。所以整理出來的是Swift版本,OC我就放棄了。 雖然Swift3 已經(jīng)有了,目前整理的這個(gè)版本是Swift2 的。Swift 3 的話有些新特性。 需要另外調(diào)整,后續(xù)有時(shí)間再整理。 

繼承CoreData有兩種方式: 

創(chuàng)建項(xiàng)目時(shí)集成

 

這種方式是自動(dòng)繼承在AppDelegate里面,調(diào)用的使用需要通過UIApplication的方式來獲取AppDelegate得到Conext。本人不喜歡這種方式,不喜歡AppDelegate太多代碼堆在一起,整理了一下這種方式

將CoreData繼承的代碼單獨(dú)解耦出來做一個(gè)單例類 

項(xiàng)目結(jié)構(gòu)圖

 

項(xiàng)目文件說明 
CoreData核心的文件就是 
1.XPStoreManager(管理CoreData的單例類) 
2.CoredataDemo.xcdatamodeld (CoreData數(shù)據(jù)模型文件)
 3.Student+CoreDataProperites.swift和Student.swift (學(xué)生對(duì)象) 
4.ViewController.swift 和Main.storyboard是示例代碼

細(xì)節(jié)代碼 

1. XPStoreManager.swift
CoreData數(shù)據(jù)管理單例類

//

// XPStoreManager.swift

// CoreDataDemo

//

// Created by xiaopin on 16/9/16.

// Copyright © 2016年 xiaopin.cnblogs.com. All rights reserved.

//

 

import CoreData

 

/// 本地?cái)?shù)據(jù)庫管理類:默認(rèn)是寫在AppDelegate的,可以這樣分離出來

class XPStoreManager {

 

 //單例寫法

 static let shareInstance = XPStoreManager()

 

 private init() {

  

 }

 

 // MARK: - Core Data stack

 

 lazy var applicationDocumentsDirectory: NSURL = {

  // The directory the application uses to store the Core Data store file. This code uses a directory named "com.pinguo.CoreDataDemo" in the application's documents Application Support directory.

  let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)

  print("\(urls[urls.count-1])")

  return urls[urls.count-1]

 }()

 

 lazy var managedObjectModel: NSManagedObjectModel = {

  // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.

  let modelURL = NSBundle.mainBundle().URLForResource("CoreDataDemo", withExtension: "momd")!

  return NSManagedObjectModel(contentsOfURL: modelURL)!

 }()

 

 lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {

  // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.

  // Create the coordinator and store

  let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

  let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")

  var failureReason = "There was an error creating or loading the application's saved data."

  do {

   try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)

  } catch {

   // Report any error we got.

   var dict = [String: AnyObject]()

   dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"

   dict[NSLocalizedFailureReasonErrorKey] = failureReason

   

   dict[NSUnderlyingErrorKey] = error as NSError

   let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)

   // Replace this 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.

   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()

   }

  }

 }

 

}

2.AppDelegate.swift 

在這個(gè)行數(shù)中加入一句代碼,退出后執(zhí)行保存一下

func applicationWillTerminate(application: UIApplication) {
  // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  // Saves changes in the application's managed object context before the application terminates.
  XPStoreManager.shareInstance.saveContext()

 }

3.Student.swift 

編寫了針對(duì)這個(gè)學(xué)生對(duì)象的增刪改查 

//

// Student.swift

// CoreDataDemo

//

// Created by cdmac on 16/9/12.

// Copyright © 2016年 xiaopin.cnblogs.com. All rights reserved.

//

 

import Foundation

import CoreData

 

class Student: NSManagedObject {

 // Insert code here to add functionality to your managed object subclass

 /*

  一般涉及到的情況有:增刪改,單對(duì)象查詢,分頁查詢(所有,條件查詢,排序),對(duì)象是否存在,批量增加,批量修改

  */

 

 /// 判斷對(duì)象是否存在, obj參數(shù)是當(dāng)前屬性的字典

 class func exsitsObject(obj:[String:String]) -> Bool {

  

  //獲取管理數(shù)據(jù)對(duì)象的上下文

  let context = XPStoreManager.shareInstance.managedObjectContext

  //聲明一個(gè)數(shù)據(jù)請(qǐng)求

  let fetchRequest = NSFetchRequest(entityName: "Student")

  

  //組合過濾參數(shù)

  let stuId = obj["stuId"]

  let name = obj["name"]

  

  //方式一

  let predicate1 = NSPredicate(format: "stuId = %@", stuId!)

  let predicate2 = NSPredicate(format: "name = %@", name!)

  //合成過濾條件

  //or ,and, not , 意思是:或與非,懂?dāng)?shù)據(jù)庫的同學(xué)應(yīng)該就很容易明白

  let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicate1,predicate2])

  //let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2])

  fetchRequest.predicate = predicate

  

  //方式二

  //fetchRequest.predicate = NSPredicate(format: "stuId = %@ or name = %@", stuId!, name!)

  //fetchRequest.predicate = NSPredicate(format: "stuId = %@ and name = %@", stuId!, name!)

  

  do{

   let fetchObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)

   

   return fetchObjects?.count > 0 ? true : false

  }catch {

   fatalError("exsitsObject \(error)")

  }

  

  return false

 }

 

 /// 添加對(duì)象, obj參數(shù)是當(dāng)前屬性的字典

 class func insertObject(obj: [String:String]) -> Bool {

  

  //如果存在對(duì)象了就返回

  if exsitsObject(obj) {

   return false

  }

  

  //獲取管理的數(shù)據(jù)上下文 對(duì)象

  let context = XPStoreManager.shareInstance.managedObjectContext

  

  //創(chuàng)建學(xué)生對(duì)象

  let stu = NSEntityDescription.insertNewObjectForEntityForName("Student",

                  inManagedObjectContext: context) as! Student

 

  //對(duì)象賦值

  let sexStr:String

  if obj["sex"] == "男"{

   sexStr = "1"

  }else{

   sexStr = "0"

  }

  let numberFMT = NSNumberFormatter()

  numberFMT.numberStyle = .NoStyle

  stu.stuId = numberFMT.numberFromString(obj["stuId"]!)

  stu.name = obj["name"]

  stu.createtime = NSDate()

  stu.sex = numberFMT.numberFromString(sexStr)

  stu.classId = numberFMT.numberFromString(obj["classId"]!)

  

  //保存

  do {

   try context.save()

   print("保存成功!")

   return true

  } catch {

   fatalError("不能保存:\(error)")

  }

  return false

 }

 

 /// 刪除對(duì)象

 class func deleteObject(obj:Student) -> Bool{

  

  //獲取管理的數(shù)據(jù)上下文 對(duì)象

  let context = XPStoreManager.shareInstance.managedObjectContext

  

  //方式一: 比如說列表已經(jīng)是從數(shù)據(jù)庫中獲取的對(duì)象,直接調(diào)用CoreData默認(rèn)的刪除方法

  context.deleteObject(obj)

  XPStoreManager.shareInstance.saveContext()

  

  //方式二:通過obj參數(shù)比如:id,name ,通過這樣的條件去查詢一個(gè)對(duì)象一個(gè),把這個(gè)對(duì)象從數(shù)據(jù)庫中刪除

  //代碼:略

  

  return true

 }

 

 /// 更新對(duì)象

 class func updateObject(obj:[String: String]) -> Bool {

  //obj參數(shù)說明:當(dāng)前對(duì)象的要更新的字段信息,唯一標(biāo)志是必須的,其他的是可選屬性

  let context = XPStoreManager.shareInstance.managedObjectContext

  

  let oid = obj["stuId"]

  let student:Student = self.fetchObjectById(Int(oid!)!)! as! Student

  

  //遍歷參數(shù),然后替換相應(yīng)的參數(shù)

  let numberFMT = NSNumberFormatter()

  numberFMT.numberStyle = .NoStyle

  

  for key in obj.keys {

   switch key {

   case "name":

    student.name = obj["name"]

   case "classId":

    student.classId = numberFMT.numberFromString(obj["classId"]!)

   default:

    print("如果有其他參數(shù)需要修改,類似")

   }

  }

  

  //執(zhí)行更新操作

  do {

   try context.save()

   print("更新成功!")

   return true

  } catch {

   fatalError("不能保存:\(error)")

  }

  

  return false

 }

 

  /// 查詢對(duì)象

 class func fetchObjects(pageIndex:Int, pageSize:Int) -> [AnyObject]? {

  //獲取管理的數(shù)據(jù)上下文 對(duì)象

  let context = XPStoreManager.shareInstance.managedObjectContext

  

  //聲明數(shù)據(jù)的請(qǐng)求

  let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Student")

  fetchRequest.fetchLimit = pageSize //每頁大小

  fetchRequest.fetchOffset = pageIndex * pageSize //第幾頁

  

  //設(shè)置查詢條件:參考exsitsObject

  //let predicate = NSPredicate(format: "id= '1' ", "")

  //fetchRequest.predicate = predicate

  

  //設(shè)置排序

  //按學(xué)生ID降序

  let stuIdSort = NSSortDescriptor(key: "stuId", ascending: false)

  //按照姓名升序

  let nameSort = NSSortDescriptor(key: "name", ascending: true)

  let sortDescriptors:[NSSortDescriptor] = [stuIdSort,nameSort]

  fetchRequest.sortDescriptors = sortDescriptors

  

  //查詢操作

  do {

   let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)

   

   //遍歷查詢的結(jié)果

   /*

   for info:Student in fetchedObjects as! [Student]{

    print("id=\(info.stuId)")

    print("name=\(info.name)")

    print("sex=\(info.sex)")

    print("classId=\(info.classId)")

    print("createTime=\(info.createtime)")

    print("-------------------")

    

   }

    */

   return fetchedObjects

  }

  catch {

   fatalError("不能保存:\(error)")

  }

  return nil

 }

 

  /// 根據(jù)ID查詢當(dāng)個(gè)對(duì)象

 class func fetchObjectById(oid:Int) -> AnyObject?{

  

  //獲取上下文對(duì)象

  let context = XPStoreManager.shareInstance.managedObjectContext

  

  //創(chuàng)建查詢對(duì)象

  let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Student")

  

  //構(gòu)造參數(shù)

  fetchRequest.predicate = NSPredicate(format: "stuId = %@", String(oid))

  

  //執(zhí)行代碼并返回結(jié)果

  do{

   let results:[AnyObject]? = try context.executeFetchRequest(fetchRequest)

   

   if results?.count > 0 {

    return results![0]

   }

  }catch{

   fatalError("查詢當(dāng)個(gè)對(duì)象致命錯(cuò)誤:\(error)")

  }

  

  return nil

 }

}

4.ViewController.swift 

具體使用: 

//

// ViewController.swift

// CoreDataDemo

//

// Created by cdmac on 16/9/11.

// Copyright © 2016年 pinguo. All rights reserved.

//

 

import UIKit

 

let cellIdentifiler = "ReuseCell"

 

class ViewController: UIViewController {

 @IBOutlet weak var txtNo: UITextField!

 @IBOutlet weak var txtName: UITextField!

 @IBOutlet weak var txtSex: UITextField!

 @IBOutlet weak var txtClassId: UITextField!

 @IBOutlet weak var tableView: UITableView!

 var dataArray:[AnyObject]?

 

 override func viewDidLoad() {

  super.viewDidLoad()

  // Do any additional setup after loading the view, typically from a nib.

  self.dataArray = Student.fetchObjects(0, pageSize: 20)

  self.tableView.reloadData()

 }

 

 override func didReceiveMemoryWarning() {

  super.didReceiveMemoryWarning()

  // Dispose of any resources that can be recreated.

 }

 

 

 @IBAction func addAction(sender: AnyObject) {

 

  var dic = [String:String]()

  

  dic["stuId"] = txtNo.text

  dic["name"] = txtName.text

  dic["sex"] = txtSex.text

  dic["classId"] = txtClassId.text

  

  if Student.insertObject(dic) {

   print("添加成功")

   self.dataArray = Student.fetchObjects(0,pageSize: 20)

   

   self.tableView.reloadData()

  }else{

   print("添加失敗")

  }

 }

 

 @IBAction func updateAction(sender: AnyObject) {

  

  var dic = [String:String]()

  

  dic["stuId"] = txtNo.text

  dic["name"] = txtName.text

  //dic["sex"] = txtSex.text

  dic["classId"] = txtClassId.text

  

  if Student.updateObject(dic) {

   print("更新成功")

   self.dataArray = Student.fetchObjects(0,pageSize: 20)

   

   self.tableView.reloadData()

  }else{

   print("更新失敗")

  }

  

 }

 

}

 

extension ViewController:UITableViewDelegate,UITableViewDataSource{

 

 //表格有多少組

 func numberOfSectionsInTableView(tableView: UITableView) -> Int {

  return 1

 }

 

 //每組多少行

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

  if self.dataArray != nil && self.dataArray?.count > 0 {

   return self.dataArray!.count

  }

  return 0

 }

 

 //高度

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

  return 50

 }

 

 //單元格加載

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

  let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifiler)

  

  let stu:Student = self.dataArray![indexPath.row] as! Student

  

  let label1:UILabel = cell?.contentView.viewWithTag(10001) as! UILabel

  let label2:UILabel = cell?.contentView.viewWithTag(10002) as! UILabel

  var sexStr = "男"

  if stu.sex?.intValue != 1 {

   sexStr = "女"

  }

  label1.text = "\(stu.stuId!) \(stu.name!) \(sexStr) \(stu.classId!)"

  label2.text = "http://xiaopin.cnblogs.com"

  

  return cell!

 }

 

 //選中

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

  

 }

 

 func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {

  return true

 }

 

 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

  if editingStyle == .Delete {

   //獲取當(dāng)前對(duì)象

   let student:Student = self.dataArray![indexPath.row] as! Student

   

   //刪除本地存儲(chǔ)

   Student.deleteObject(student)

   

   //刷新數(shù)據(jù)源

   self.dataArray?.removeAtIndex(indexPath.row)

   //self.dataArray = Student.fetchObjects(0, pageSize: 20)

   

   //刪除單元格

   tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

  }

 }

 

 func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {

  return .Delete

 }

 

 func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {

  return "刪除"

 }

}

運(yùn)行效果圖

 

源碼下載:CoreDataDemo.zip

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 詳解iOS App開發(fā)中Cookie的管理方法

    詳解iOS App開發(fā)中Cookie的管理方法

    iOS中主要靠NSHTTPCookieStorage和NSHTTPCookie來管理Cookie,下面我們就來詳解iOS App開發(fā)中Cookie的管理方法,在最后一部分會(huì)單獨(dú)整理出如何清除Cookie的方法.
    2016-07-07
  • iOS利用NSMutableAttributedString實(shí)現(xiàn)富文本的方法小結(jié)

    iOS利用NSMutableAttributedString實(shí)現(xiàn)富文本的方法小結(jié)

    這篇文章主要給大家介紹了關(guān)于iOS利用NSMutableAttributedString如何實(shí)現(xiàn)富文本的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • 詳解使用Xcode進(jìn)行iOS設(shè)備無線調(diào)試

    詳解使用Xcode進(jìn)行iOS設(shè)備無線調(diào)試

    這篇文章主要介紹了詳解使用Xcode進(jìn)行iOS設(shè)備無線調(diào)試,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-12-12
  • 剖析iOS開發(fā)中Cocos2d-x的內(nèi)存管理相關(guān)操作

    剖析iOS開發(fā)中Cocos2d-x的內(nèi)存管理相關(guān)操作

    這篇文章主要介紹了剖析iOS開發(fā)中Cocos2d-x的內(nèi)存管理相關(guān)操作,Cocos2d-x是開發(fā)游戲的利器,需要的朋友可以參考下
    2015-10-10
  • IOS開發(fā)壓縮后圖片模糊問題解決

    IOS開發(fā)壓縮后圖片模糊問題解決

    這篇文章主要為大家介紹了IOS開發(fā)壓縮后圖片模糊問題解決實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-07-07
  • iOS實(shí)現(xiàn)折疊單元格

    iOS實(shí)現(xiàn)折疊單元格

    這篇文章主要為大家詳細(xì)介紹了iOS實(shí)現(xiàn)折疊單元格,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-09-09
  • iOS去除Webview鍵盤頂部工具欄的方法

    iOS去除Webview鍵盤頂部工具欄的方法

    這篇文章主要給大家介紹了關(guān)于iOS去除Webview鍵盤頂部工具欄的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)各位iOS開發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • iOS開發(fā)技巧之WeakSelf宏的進(jìn)化詳解

    iOS開發(fā)技巧之WeakSelf宏的進(jìn)化詳解

    在程序中我們經(jīng)常用到Block,但寫weak self 時(shí)會(huì)比較繁瑣,下面這篇文章主要給大家介紹了關(guān)于iOS開發(fā)技巧之WeakSelf宏的進(jìn)化的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們一起來看看吧
    2018-05-05
  • iOS把圖片緩存到本地的幾種方法(總結(jié))

    iOS把圖片緩存到本地的幾種方法(總結(jié))

    下面小編就為大家分享一篇iOS把圖片緩存到本地的幾種方法總結(jié),具有很的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • ios實(shí)現(xiàn)底部PopupWindow的示例代碼(底部彈出菜單)

    ios實(shí)現(xiàn)底部PopupWindow的示例代碼(底部彈出菜單)

    這篇文章主要介紹了ios實(shí)現(xiàn)底部PopupWindow的示例代碼(底部彈出菜單),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-01-01

最新評(píng)論