Swift教程_CoreData实例(三)_构建控制层(列表数据加载、删除数据)

简介:

Swift教程_CoreData实例(一)_构建storyboard

Swift教程_CoreData实例(二)_构建数据层

Swift教程_CoreData实例(三)_构建控制层(列表数据加载、删除数据)

Swift教程_CoreData实例(四)_构建控制层(查询、更新数据)

Swift教程_CoreData实例(五)_构建控制层(添加数据)

四、构建控制层

控制层总体结构包括列表的数据加载、数据的新增、删除、更新。这里我们先来搞定列表controller的功能(数据加载、删除),即PKOBooksTableViewController

1.列表数据加载、删除数据

我们自定义一个列表控制器PKOBooksTableViewController,并应用到storyboard的列表中。通过NSFetchedResultsController对象来查询、删除数据。

代码如下,注释非常详尽:

[objc]  view plain  copy
  1. import UIKit  
  2. import CoreData  
  3.   
  4. class PKOBooksTableViewController: UITableViewController,NSFetchedResultsControllerDelegate {  
  5.       
  6.     var managedObjectContext: NSManagedObjectContext?  
  7.     //获取数据的控制器  
  8.     var fetchedResultsController: NSFetchedResultsController?  
  9.       
  10.     override func viewDidLoad() {  
  11.         super.viewDidLoad()  
  12.           
  13.         //为导航栏左边按钮设置编辑按钮  
  14.         self.navigationItem.leftBarButtonItem = self.editButtonItem()  
  15.           
  16.         //执行获取数据,并处理异常  
  17.         var error: NSError? = nil  
  18.         if !self.initFetchedResultsController().performFetch(&error){  
  19.             NSLog("Unresolved error \(error), \(error!.userInfo)")  
  20.             abort()  
  21.         }  
  22.     }  
  23.       
  24.     override func didReceiveMemoryWarning() {  
  25.         super.didReceiveMemoryWarning()  
  26.     }  
  27.       
  28.     //设置单元格的信息  
  29.     func setCellInfo(cell: UITableViewCell, indexPath: NSIndexPath) {  
  30.         var book = self.fetchedResultsController?.objectAtIndexPath(indexPath) as Book  
  31.         NSLog("======\(book.title)")  
  32.         cell.textLabel.text = book.title  
  33.     }  
  34.       
  35.     // MARK: - Table view data source  
  36.       
  37.     override func numberOfSectionsInTableView(tableView: UITableView) -> Int {  
  38.         //分组数量  
  39.         return self.fetchedResultsController!.sections!.count  
  40.     }  
  41.       
  42.     override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {  
  43.         //每个分组的数据数量  
  44.         var section = self.fetchedResultsController!.sections![section] as NSFetchedResultsSectionInfo  
  45.         return section.numberOfObjects  
  46.     }  
  47.       
  48.       
  49.     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {  
  50.         let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell  
  51.         // 为列表Cell赋值  
  52.         self.setCellInfo(cell, indexPath: indexPath)  
  53.         return cell  
  54.     }  
  55.       
  56.     override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {  
  57.         //分组表头显示  
  58.         return self.fetchedResultsController!.sections![section].name  
  59.     }  
  60.       
  61.     /* 
  62.     // Override to support conditional editing of the table view. 
  63.     override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
  64.     // Return NO if you do not want the specified item to be editable. 
  65.     return true 
  66.     } 
  67.     */  
  68.       
  69.     // 自定义编辑单元格时的动作,可编辑样式包括UITableViewCellEditingStyleInsert(插入)、UITableViewCellEditingStyleDelete(删除)。  
  70.     override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {  
  71.         if editingStyle == .Delete {  
  72.             //删除sqlite库中对应的数据  
  73.             var context = self.fetchedResultsController?.managedObjectContext  
  74.             context!.deleteObject(self.fetchedResultsController?.objectAtIndexPath(indexPath) as NSManagedObject)  
  75.             //删除后要进行保存  
  76.             var error: NSError? = nil  
  77.             if context?.save(&error) == nil {  
  78.                 NSLog("Unresolved error \(error), \(error!.userInfo)")  
  79.                 abort()  
  80.             }  
  81.         } else if editingStyle == .Insert {  
  82.         }  
  83.     }  
  84.       
  85.     /* 
  86.     // Override to support rearranging the table view. 
  87.     override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { 
  88.      
  89.     } 
  90.     */  
  91.       
  92.     // Override to support conditional rearranging of the table view.  
  93.     override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {  
  94.         // 移动单元格时不要重新排序  
  95.         return false  
  96.     }  
  97.       
  98.     // MARK: - NSFetchedResultsController delegate methods to respond to additions, removals and so on.  
  99.       
  100.     //初始化获取数据的控制器  
  101.     func initFetchedResultsController() ->NSFetchedResultsController  
  102.     {  
  103.         if self.fetchedResultsController != nil {  
  104.             return self.fetchedResultsController!  
  105.         }  
  106.         // 创建一个获取数据的实例,用来查询实体  
  107.         var fetchRequest = NSFetchRequest()  
  108.         var entity = NSEntityDescription.entityForName("Book", inManagedObjectContextself.managedObjectContext!)  
  109.         fetchRequest.entity = entity  
  110.           
  111.         // 创建排序规则  
  112.         var authorDescriptor = NSSortDescriptor(key: "author", ascendingtrue)  
  113.         var titleDescriptor = NSSortDescriptor(key: "title", ascendingtrue)  
  114.         var sortDescriptors = [authorDescriptor, titleDescriptor]  
  115.         fetchRequest.sortDescriptors = sortDescriptors  
  116.           
  117.         // 创建获取数据的控制器,将section的name设置为author,可以直接用于tableViewSourceData  
  118.         var fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContextself.managedObjectContext!, sectionNameKeyPath"author", cacheName"Root")  
  119.         fetchedResultsController.delegate = self  
  120.         self.fetchedResultsController = fetchedResultsController  
  121.         return fetchedResultsController  
  122.     }  
  123.       
  124.     //通知控制器即将开始处理一个或多个的单元格变化,包括添加、删除、移动或更新。在这里处理变化时对tableView的影响,例如删除sqlite数据时同时要删除tableView中对应的单元格  
  125.     func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {  
  126.         switch(type) {  
  127.         case .Insert:  
  128.             self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)  
  129.         case .Delete:  
  130.             self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)  
  131.         case .Update:  
  132.             self.setCellInfo(self.tableView.cellForRowAtIndexPath(indexPath!)!, indexPath: indexPath!)  
  133.         case .Move:  
  134.             self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)  
  135.             self.tableView.insertRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)  
  136.         }  
  137.     }  
  138.       
  139.     //通知控制器即将开始处理一个或多个的分组变化,包括添加、删除、移动或更新。  
  140.     func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {  
  141.         switch(type) {  
  142.         case .Insert:  
  143.             self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Automatic)  
  144.         case .Delete:  
  145.             self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Automatic)  
  146.         case .Update:  
  147.             break  
  148.         case .Move:  
  149.             break  
  150.         }  
  151.     }  
  152.   
  153.     //通知控制器即将有变化  
  154.     func controllerWillChangeContent(controller: NSFetchedResultsController) {  
  155.         //tableView启动变更,需要endUpdates来结束变更,类似于一个事务,统一做变化处理  
  156.         self.tableView.beginUpdates()  
  157.     }  
  158.       
  159.     //通知控制器变化完成  
  160.     func controllerDidChangeContent(controller: NSFetchedResultsController) {  
  161.         self.tableView.endUpdates()  
  162.     }  
  163.     /* 
  164.     // MARK: - Navigation 
  165.      
  166.     // In a storyboard-based application, you will often want to do a little preparation before navigation 
  167.     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
  168.     // Get the new view controller using [segue destinationViewController]. 
  169.     // Pass the selected object to the new view controller. 
  170.     } 
  171.     */  
  172.       
  173. }  



原文地址:http://blog.csdn.net/ooppookid/article/details/40867835

相关文章
|
4月前
|
IDE 开发工具 Swift
Swift语言的教程
Swift语言的教程
49 1
|
Swift 编译器
Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析
本文主要探究: 当一个类遵循了协议,且协议和类都有方法实现时,实例对象调用方法的优先顺序
Swift - 实例对象调用协议方法优先级分析/ witness_methos witness_table分析
|
Swift
最新Swift学习教程-从简单到复杂 韩俊强的博客
GitHub每日更新地址: https://github.com/iOS-Swift-Developers/Swift Swift基础知识大全,Swift学习从简单到复杂,不断地完善与更新, 欢迎Star️,欢迎Fork,️iOS开发者交流群:446310206 知识架构: 常两变量 基.
1174 0
|
iOS开发 Swift 编译器
使用 Swift 在 iOS 10 中集成 Siri —— SiriKit 教程
使用 Swift 在 iOS 10 中集成 Siri —— SiriKit 教程 转载地址:http://swift.gg/2016/06/28/adding-siri-to-ios-10-apps-in-swift-tutorial/ 下载 Xcode 8,配置 iOS 10 和 Swift 3 (可选)通过命令行编译 除非你想使用命令行编译,使用 Swift 3.0 的工具链并不需要对项目做任何改变。
1734 0
|
Swift
SWIFT 之CoreData初试
SWIFT中使用CoreData来保存本地数据,在建立项目的时候把 "Use Core Data"选项选上 项目建立完成后点击后缀为 .xcdatamodeld的那个文件,点击右下角"Add Entity"添加一个Entity后可以修改其名称,接着在"Attributes"下面点击“+”号添加...
776 0
|
JSON 数据格式 Swift
Swift语言中如何使用JSON数据教程
原文:Swift语言中如何使用JSON数据教程 这是一篇翻译文章,原文出处:http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial   Swift语言中如何使用JSON数据教程   JSON(全称:JavaScript Object Notation),是网络服务中传输数据的常用方法,JSON因为容易使用,且可读性强, 所以非常受到欢迎。
1137 0
|
Android开发 Swift
swift UI专项训练24 构建函数和侦测网页载入事件
     构建一个方法用来载入网页的请求: func loadurl(url:String ,web:UIWebView){ let aurl = NSURL(string: ur...
760 0
|
缓存 Swift
Swift实战-豆瓣电台(四)歌曲列表的展现
原文:Swift实战-豆瓣电台(四)歌曲列表的展现 观看地址 http://v.youku.com/v_show/id_XNzMwNDE0OTA4.html 这节的主要内容是如何利用cell展现获取到的数据。
782 0