Hola Amigos!
I’m going to demonstrate how easily you can make a simple list using Core Data with operations of Add, Delete, and Update.
Vamonos!
Make a new project, and make sure that Use Core Data is checked.
When project is created, from explorer; click .xcdatamodeld.Then click Add Entity, rename it to Shows, and in the Attributes section click the + and add an item of name watchList of type string.
After that open your MainStoryboard. Drag and drop a TextField, a Button, a TableView, and may be a Navigation Bar if you like.
Import CoreData and make outlets for tableview and textfield, and an action event for button.
After being done with that open your ViewController. Create the following variables.
var watchList = [NSManagedObject]() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
Now we will create a function that we will use to add values to Core Data.
func addShow(showName: String){ let managedContext = appDelegate.managedObjectContext! let entity = NSEntityDescription.entityForName("Shows", inManagedObjectContext: managedContext) let show = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) show.setValue(showName, forKey: "watchList") var error: NSError? if !managedContext.save(&error) { println("Could not save (error), (error?.userInfo)") } watchList.append(show) }
Then in your Button action function.
@IBAction func add(sender: AnyObject) { self.addShow(showToAdd.text) self.tableView.reloadData() showToAdd.text = "" }
And in your numberOfRowsInSection, and cellForRowAtIndexPath functions of UITableViewDataSource.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return watchList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell let shows = watchList[indexPath.row] cell.textLabel!.text = shows.valueForKey("watchList") as! String? return cell }
Run your app. I have added the names of shows that I want to watch.
Now stop the app and run your app again you won’t see the records you recently added.
To see the records you added you need to fetch them. So in your viewWillAppear.
override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let managedContext = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName:"Shows") var error: NSError? let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]? if let results = fetchedResults { watchList = results } else { println("Could not fetch (error), (error!.userInfo)") } }
Run again.
Since we’re done with adding, and fetching. we’ll go for some deletion of records from Core Data. For that we will use UITableViewDataSource‘s function, tableView(_:commitEditingStyle:forRowAtIndexPath:).
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let managedContext:NSManagedObjectContext = appDelegate.managedObjectContext! managedContext.deleteObject(watchList[indexPath.row] as NSManagedObject) watchList.removeAtIndex(indexPath.row) managedContext.save(nil) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } }
Run your app and slide from right to left.
After Delete operation is performed.
You can also double check the deletion by re-running the app.
For this purpose we are going to create two functions. 1st function will generate an alert with a textfield, whenever a user selects a cell, and the other will be handling the updates in Core Data.
//Receives the index of selected cell from didSelectRowAtIndexPath func updateAlertView(cellIndex: Int){ var alert = UIAlertController(title: "Show", message: "Update show name", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Update", style: .Default) { (action: UIAlertAction!) -> Void in let textField = alert.textFields![0] as! UITextField; self.updateCoreData(textField.text,index: cellIndex) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction!) -> Void in } alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in }; alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } //Updates in Core Data func updateCoreData(value: String, index: Int){ var managedContext: NSManagedObjectContext = appDelegate.managedObjectContext! var fetchRequest = NSFetchRequest(entityName: "Shows") if let fetchResults = appDelegate.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] { if fetchResults.count != 0{ var managedObject = fetchResults[index] managedObject.setValue(value, forKey: "watchList") managedContext.save(nil) } } }
Finally, in didSelectRowAtIndexPath of UITableViewDelegate.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { updateAlertView(indexPath.row) }
Build and run, then select a cell.
I updated the value of cell “Jessica Jones” to “Hellsing Ultimate”.
So, there you go. A simple list using Core Data in Swift.
You can download this project from here.
Adiós!
This article covers some important things you must know when you are considering a move…
What is Unit Testing? In its simplest term, unit testing is testing a small piece…
In this article, you will learn about a type of Creational Design Pattern which is…
In this tutorial, you will go through the use of targets to achieve two separate…
In this article, you will learn about a type of Structural Design Pattern which is…
In this article you will learn about a type of Creational Design Pattern which is…
View Comments
Nicely done!