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.

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.

Now stop the app and run your app again you won’t see the records you recently added.

Fetching Values From Core Data

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

 

Run again.

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.

After Delete operation is performed.

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.

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!

Share:

administrator

2 Comments

Leave a Reply

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