牛骨文教育服务平台(让学习变的简单)
博文笔记

iOS Swift教程 Core Data (一)Hello Core Data

创建时间:2014-12-28 投稿人: 浏览次数:1779

正在学习swift的Core Data,做个笔记,顺便分享源码

转载请注明出处:http://blog.csdn.net/yamingwu/article/details/42215541

这个实例是一个很简单的Table,通过右上角的Add按钮可以添加新的用户名。数据存储在CoreData中,这样,才不会丢失。

通过这个例子可以学会:

  1. 使用Xcode的model编辑器创建数据对象的model data。

  2. 添加新的记录到CoreData中

  3. 从CoreData中获取记录集合

  4. 显示记录到table view中


这个例子十分简单,还有很多可以改进的地方,比如,每次要操作managed class都需要访问AppDelegate,读取和存储数据使用的是KVC(key-value coding )方式而不是类似于类操作的方式。

程序截图和源码地址:

https://github.com/dnawym/StudySwift/tree/master/CoreData/HitList

  1. 在创建工程时选择使用core data
  2. 编辑.xcdatamodeld文件,添加entity person,添加attribute name,类型为String
  3. 初始化,读取和修改core data数据
  4.     @IBOutlet weak var tableView: UITableView!
        
        var people = [NSManagedObject]()
  5. 从Core Data数据库中读取数据

  6.     override func viewWillAppear(animated: Bool) {
            let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
            
            let managedContext = appDelegate.managedObjectContext!
            
            let fetchRequest = NSFetchRequest(entityName: "Person")
            
            var error: NSError?
            
            let fetchResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
            
            if let results = fetchResults {
                people = results
            } else {
                println("Could not fetch (error), (error!.userInfo)")
            }
        }
  7. 读取数据填入table view中

  8.     // MARK: UITableViewDataSource
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return people.count
        }
        
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
            
            let person = people[indexPath.row]
            cell.textLabel?.text = person.valueForKey("name") as String?
            
            return cell
        }
  9. 添加用户名并保存到Core Data数据库中

  10.     // MARK: private
        func saveName(name: String) {
            let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
            let managedContext = appDelegate.managedObjectContext!
            
            let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
            
            let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
            
            person.setValue(name, forKey: "name")
            
            var error:NSError?
            if !managedContext.save(&error) {
                println("Could not save (error), (error?.userInfo)")
            }
            
            people.append(person)
        }
        
        @IBAction func addName(sender: AnyObject) {
            
            var alert = UIAlertController(title: "New name", message: "Add a new name", preferredStyle: UIAlertControllerStyle.Alert)
            
            let saveAction = UIAlertAction(title: "Save", style: .Default, handler: {
                (action: UIAlertAction!) -> Void in
                let textField = alert.textFields![0] as UITextField
                self.saveName(textField.text)
                self.tableView.reloadData()
            })
            
            let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: {
                (action: UIAlertAction!) -> Void in
            })
            
            alert.addTextFieldWithConfigurationHandler({
                (textField: UITextField!) -> Void in
            })
            
            alert.addAction(saveAction)
            alert.addAction(cancelAction)
            
            presentViewController(alert, animated: true, completion: nil)
        }



声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。