CoreData實踐(四)——查詢資料

乞力馬紮羅的雪CYF發表於2015-09-17

     我在上一篇部落格中講解了如何往SQLite資料庫中插入資料,現在我們將要進行查詢。

(1)程式碼實現如下:

import UIKit
import CoreData

class UsersTableViewController: UITableViewController {

  var dataArr:Array<AnyObject>! = []
  var context:NSManagedObjectContext!
  
    override func viewDidLoad() {
        super.viewDidLoad()

      
      context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
      
      var f = NSFetchRequest(entityName: "Users")
     dataArr = context.executeFetchRequest(f, error: nil)
      
      
    }

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

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return dataArr.count
    }

  
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell

      
      var name = dataArr[indexPath.row].valueForKey("name") as! String
      var age = dataArr[indexPath.row].valueForKey("age") as! Int

      var label = cell.viewWithTag(101) as! UILabel
      label.text = "姓名:\(name);  年齡:\(age)"
      
      
      

        return cell
    }

}

(2)執行程式,結果如下:


github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!

相關文章