iOS学习- 21 Core Data by Tutorials - CH01

First app with core data

  • model data you want to store in Core Data using Xcode's model editor
  • add new records to Core Data
  • fetch a set of records from Core Data; and 
  • display the fetched results to the user in a table view
Add a Table View Controller and embed a navigator controller  :






Saving step:


func saveName(name: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

//2
let entity = NSEntityDescription.entityForName("Person",
inManagedObjectContext:managedContext)
let person = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)

//3
person.setValue(name, forKey: "name")
//4
do {
try managedContext.save()

//5
people.append(person)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}



Fetching step:

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

//2
let fetchRequest = NSFetchRequest(entityName: "Person")
//3
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
people = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}

}



//=======================================================================================================

TableviewController.swift 


//
//  TableViewController.swift
//  HitList
//
//  Created by Ricky Choi on 16/6/11.
//  Copyright © 2016年 worm. All rights reserved.
//


import UIKit
import CoreData


class TableViewController: UITableViewController {


    @IBAction func addName(sender: AnyObject) {
        var alert = UIAlertController(title: "Adding Name", message: "Please input a Name", preferredStyle: UIAlertControllerStyle.Alert)
        
        let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) { (action: UIAlertAction) in
            let textField = alert.textFields![0] as UITextField
            
            //self.names.append(textField.text!)
            //self.tableView.reloadData()
            
            self.saveName(textField.text!)
            
            
            //animate
            let indexPath = NSIndexPath(forRow: self.people.count - 1, inSection: 0)
            self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
        
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default) { (action: UIAlertAction) in
            
        }
        
        alert.addAction(saveAction)
        alert.addAction(cancelAction)
        
        alert.addTextFieldWithConfigurationHandler { (textfield: UITextField) in
            
        }
        
        self.presentViewController(alert, animated: true) { 
            
        }
        
    }
    
    func saveName(text: String) {
        //1 application delegate
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
        let managedObjectContents = appDelegate.managedObjectContext
        
        //2 create a entity
        let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedObjectContents)
        
        let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContents)
        
        //3. save text value to  person
        person.setValue(text, forKey: "name")
        
        //4 save entity to mananged object context
        //var error: NSError?
        do {
            try managedObjectContents.save()
            //5 save to array , update UI
            people.append(person)
        } catch {
        
            let nserror = error as NSError
            print("Can not save \(nserror),\(nserror.userInfo)")
        }
        
        //if (managedObjectContents.save(&error) == nil) {
        //    print("Can not save \(error),\(error?.userInfo)")
        //}
        
        //5 save to array, update UI
        //people.append(person)
        
    }
    
    //store name array
    var names = [String]()
    //core data object
    var people = [NSManagedObject]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "Name List"
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false


        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }


    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //1 application delegate
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
        let managedObjectContents = appDelegate.managedObjectContext
        
        //2 create a fetch request
        let fetchRequest = NSFetchRequest(entityName: "Person")
        
        //3 run request
        do {
            let fetchRequest = try managedObjectContents.executeFetchRequest(fetchRequest) as! [NSManagedObject]
            people = fetchRequest
            self.tableView.reloadData()
        } catch {
            let nserror = error as NSError
            print("Can not Fetch \(nserror),\(nserror.userInfo)")
        }
        
        
    }
    
    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 Incomplete implementation, return the number of sections
        return 1
    }


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        //return 0
        //return names.count
        return people.count
    }


    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
        
        // Configure the cell...
        //cell.textLabel?.text = names[indexPath.row]
        let person = people[indexPath.row]
        cell.textLabel?.text = person.valueForKey("name") as! String
        return cell
    }
    


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */


    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */


    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {


    }
    */


    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */


    /*
    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值