CoreData实践(四)——查询数据

来源:互联网 发布:寡妇王二娘 知乎 编辑:程序博客网 时间:2024/06/01 10:28

     我在上一篇博客中讲解了如何往SQLite数据库中插入数据,现在我们将要进行查询。

(1)代码实现如下:

import UIKitimport CoreDataclass 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  。欢迎大家访问!

1 0
原创粉丝点击