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
Saving step:
//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.
}
*/
}