码迷,mamicode.com
首页 > 移动开发 > 详细

ios开发中使用coreData来数据存储及获取

时间:2015-03-15 23:29:57      阅读:2761      评论:0      收藏:0      [点我收藏+]

标签:

系统:mac 10.9.5  编辑器:xcode 6.1   语言:swift

新建一个single view application,将use core Data勾选。

在xcode最左侧会有一个xxx.xcdatamodeld文件,点击添加一个entity,并双击重命名为Person。然后点击添加属性,命名为name,类型选string。到此数据模型就构造好了。

以一个数组的存储为例:

拖一个tableviewcontroller视图到故事板中,并新建一个类与视图关联,在文件结构中找到cell,改写identifier为cell。在下面代码135行中同步改成cell。

然后在故事板中添加一个顶部导航,和add按钮并将按钮关联到viewcontroller中。

代码如下:

  1 //
  2 //  TableViewController.swift
  3 //  练习tableview
  4 //
  5 //  Created by xiaos on 15-3-15.
  6 //  Copyright (c) 2015年 xiaos. All rights reserved.
  7 //
  8 
  9 import UIKit
 10 import CoreData
 11 
 12 class TableViewController: UITableViewController {
 13     
 14     //添加姓名按钮
 15     @IBAction func addName(sender: AnyObject) {
        //以警告框的形式
16 var alert = UIAlertController(title: "添加", message:"添加一个名字", preferredStyle: UIAlertControllerStyle.Alert) 17 //保存按钮 18 let saveAction = UIAlertAction(title: "保存", style: UIAlertActionStyle.Default,handler: {(action:UIAlertAction!) -> Void in 19 20 let textField = alert.textFields![0] as UITextField
          //调用下面的saveName方法
21 self.saveName(textField.text) 22 // self.tableView.reloadData()

         //定义一个路径来确定插入单元格的位置 和 设置插入动画 23 let indexPath = NSIndexPath(forRow: (self.people.count-1), inSection: 0) 24 self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left) 25 26 }) 27 //取消按钮 28 let cannelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default,handler: nil) 29 //在alert中添加按钮 30 alert.addAction(saveAction) 31 alert.addAction(cannelAction) 32 //在alert中添加文本框 33 alert.addTextFieldWithConfigurationHandler { (textField:UITextField!) -> Void in} 34 35 36 //在视图中弹出alert 37 self.presentViewController(alert, animated: true, completion: nil) 38 39 40 41 42 43 44 } 45 46 //保存数据,分5个步骤 47 func saveName(name:String){ 48 49 //1、取得总代理和托管对象内容总管 50 let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 51 52 let managedContext = appDelegate.managedObjectContext! 53 54 //2、建立一个entity 55 let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext) 56 57 let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) 58 59 //3、保存文本框中的值到person 60 person.setValue(name, forKey: "name") 61 62 //4、保存entity到托管对象总管中 63 var error:NSError? 64 if !managedContext.save(&error){ 65 println("Could not save \(error),\(error?.userInfo)") 66 } 67 //5、保存到数组中,更新ui 68 people.append(person) 69 } 70 71 //姓名字典 72 73 74 //core data对象 75 var people = [NSManagedObject]() 76 77 78 override func viewDidLoad() { 79 super.viewDidLoad() 80 81 // title = "列表" 82 // Uncomment the following line to preserve selection between presentations 83 // self.clearsSelectionOnViewWillAppear = false 84 85 // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 86 // self.navigationItem.rightBarButtonItem = self.editButtonItem() 87 } 88 89 //获取数据 分3步 90 override func viewDidAppear(animated: Bool) { 91 //1、取得总代理和托管对象内容总管 92 let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate 93 94 let managedContext = appDelegate.managedObjectContext! 95 //2、建立一个获取的请求 96 let fetchRequest = NSFetchRequest(entityName: "Person") 97 98 //3、执行请求 99 var error:NSError? 100 101 let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]? 102 103 if let results = fetchedResults{ 104 people = results 105 self.tableView.reloadData() 106 }else{ 107 println("Could not save \(error),\(error?.userInfo)") 108 } 109 110 } 111 112 override func didReceiveMemoryWarning() { 113 super.didReceiveMemoryWarning() 114 // Dispose of any resources that can be recreated. 115 } 116 117 // MARK: - Table view data source 118 119 //表格部分 120 override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 121 // #warning Potentially incomplete method implementation. 122 // Return the number of sections. 123 return 1 124 } 125 126 //表格行数 127 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 128 // #warning Incomplete method implementation. 129 // Return the number of rows in the section. 130 return people.count 131 } 132 133 //cell的内容 134 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 135 let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell 136 137 cell.textLabel?.text = people[indexPath.row].valueForKey("name") as String? 138 139 140 return cell 141 } 142 143 144 /* 145 // Override to support conditional editing of the table view. 146 override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 147 // Return NO if you do not want the specified item to be editable. 148 return true 149 } 150 */ 151 152 /* 153 // Override to support editing the table view. 154 override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 155 if editingStyle == .Delete { 156 // Delete the row from the data source 157 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 158 } else if editingStyle == .Insert { 159 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 160 } 161 } 162 */ 163 164 /* 165 // Override to support rearranging the table view. 166 override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { 167 168 } 169 */ 170 171 /* 172 // Override to support conditional rearranging of the table view. 173 override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { 174 // Return NO if you do not want the item to be re-orderable. 175 return true 176 } 177 */ 178 179 /* 180 // MARK: - Navigation 181 182 // In a storyboard-based application, you will often want to do a little preparation before navigation 183 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 184 // Get the new view controller using [segue destinationViewController]. 185 // Pass the selected object to the new view controller. 186 } 187 */ 188 189 }

 

ios开发中使用coreData来数据存储及获取

标签:

原文地址:http://www.cnblogs.com/lovecc/p/4340686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!