How to Use Realm with Swift

Hello friends, in this article we will talk about what is Realm and how to use it. When developing mobile applications with iOS, we often need to store some data on the user’s device. While this is very simple data at times, it can go as far as establishing a database at other times. At such times, you can use Core Data, SQLite or Realm. If you want to get more details about Realm, you can find it here.

Project Plan

In the sample project we will do, users will be able to record and see the movies they watch. In addition, they can delete or update the movies they have added. The sample working image is as follows.

A movie list page and add movies to list page are required. We will also turn it into an update page with small touches on the adding film to the list page. I leave the design parts aside because you can reach the project at the end of the article.

Model Building

In order to add a model to the Real database we will create, we need to create a model suitable for the database. The model we create must inherit from the Object class. The Object class is actually a class that comes with the Real pod and creates the Base Model. Then I create whatever properties I want in my Movie class. I define it with Dynamic type because when the data changes in one place, I want it to change quickly on all sides. It is enough for me to create id, movieName and createdDate in my Movie class. In this model, I also create a Create function, with this function, when we call it a movie, a Movie class is returned to you.

Listing

The listing process is actually very simple. The same objects saved in the Realm database are kept in one place and when you want to retrieve these recorded objects, Realm gives you your objects in the Result. After this process, you can use the objects.

Add and Update

You can update and add with the Realm.write function as follows. If you are going to update, it is enough to change the name of the object that comes dynamically in Realm.write. If you are going to add, you can do it with the realm.add() function as follows.

Delete

The delete operation is very similar to the insert operation, the only difference is that you use the delete function instead of the create function. You can delete the object you want to delete with the delete function.

In fact, although it is very simple and easy to use, there are a few advanced parts. Like how to migrate the database we created. In order for this article not to be too long, I will talk about them in another article. You can find that article here. You can find the project we created in this article here.

If you have questions, you can reach us by sending an e-mail or comment. Good work.

 

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.