Greetings Humans!
I was thinking for a long time to write about Realm. So…
What is Realm?
Realm is an open source client side database for Mobile platforms. Read more on their web page.
Its quite easy to use and less complicated as compared to Core Data. In this tutorial I am going to guide you through basic functions of it which are Add, Update and Delete.
Setting Up Project
Create a project and initiate a pod in it, then open the pod file and paste the following snippet in it.
After that save it and install the pod. It might take some time to install.
If you don’t want to use pod to install Realm, you can also download the required files and drag it in your project.
And your project is ready.
Constraining the View Controller
I have made a View Controller and created all the outlets and actions of the views on it.
Adding Model Class
Additionally, I also have created a Model class which in other words you can say table. With id as the primary key.
Adding Object to Realm
Now, open your ViewController class and add two variables to it.
We are going to create a function to check if Realm already contains the primary key we are trying to add in.
I have also created some helper functions.
Finally, In action of your Done button. Every transaction (add, update or delete) in Realm needs to be done inside a write block. So first we initialized the object of Model class, then we passed data to the properties inside it and then added it to realm.
Updating Object in Realm
Updating procedure is somewhat similar to adding object, but first we search for the object we want to change and then update it. This code will go inside your Update button action.
Deleting Object from Realm
Deleting is pretty straight forward. Check if the object exists in realm, then inside write block delete it from realm.
Displaying on TableView
In datasource functions of the tableview.
Lastly, Build and run it. I got the following results.
The source code can be found here.
If you have any questions please leave a comment.
Good day!
4 Comments