Press "Enter" to skip to content

Making a simple list of “Shows to Watch” in iOS using Core Data

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.
Screen Shot 2015-11-14 at 11.19.08 am

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.
Screen Shot 2015-11-14 at 12.41.30 pm

After that open your MainStoryboard. Drag and drop a TextField, a Button, a TableView, and may be a Navigation Bar if you like.
Screen Shot 2015-11-14 at 12.47.41 pm

Import CoreData and make outlets for tableview and textfield, and an action event for button.
Screen Shot 2015-11-14 at 12.52.41 pm

After being done with that open your ViewController. Create the following variables.

Adding Values To Core Data

Now we will create a function that we will use to add values to Core Data.

Then in your Button action function.

 

And in your numberOfRowsInSection, and cellForRowAtIndexPath functions of UITableViewDataSource.

 

Run your app. I have added the names of shows that I want to watch.
iOS Simulator Screen Shot 14-Nov-2015 1.15.51 pm

Now stop the app and run your app again you won’t see the records you recently added.
iOS Simulator Screen Shot 14-Nov-2015 1.17.59 pm

Fetching Values From Core Data

To see the records you added you need to fetch them. So in your viewWillAppear.

 

Run again.
iOS Simulator Screen Shot 14-Nov-2015 1.18.56 pm

Deleting Values From Core Data

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:).

 

Run your app and slide from right to left.
iOS Simulator Screen Shot 14-Nov-2015 6.26.13 pm

After Delete operation is performed.
iOS Simulator Screen Shot 14-Nov-2015 6.28.32 pm

You can also double check the deletion by re-running the app.

Updating Values

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.

 

Finally, in didSelectRowAtIndexPath of UITableViewDelegate.

 

Build and run, then select a cell.
iOS Simulator Screen Shot 14-Nov-2015 7.27.48 pm

I updated the value of cell “Jessica Jones” to “Hellsing Ultimate”.
iOS Simulator Screen Shot 14-Nov-2015 7.27.55 pm

So, there you go. A simple list using Core Data in Swift.
You can download this project from here.
Adiós!

Author: kodesnippets

2 Comments

  1. Aaron
    Aaron December 7, 2015

    Nicely done!

Leave a Reply

Your email address will not be published. Required fields are marked *