CRUD Operation Using RealmSwift Part 1

  1. What is Realm
  2. RealmSwift
  3. Creating a Complex Realm Model
  4. Why we use @objc and dynamic in Property
  5. To-One and To-Many Relationship in Realm
  6. How to store Custom enum in Realm
  7. What is RealmOptional and How to Store Swift Optional Atomic Property
  8. How Computed Property works as Transient Property In realm
  9. How to do indexing for performance gain
  10. What is Linking Object in Realm
  11. Complex Predicate Queries
  12. CRUD Operation
  13. What is Live Results in Realm
  14. Things avoided when Modify Realm Objects

Realm

RealmSwift

Getting Started

Figure 1

User Model

  1. First we inherit User class from Object which makes it Realm Object . Realm objects are basically a standard data model, much like any other standard data model you’ve defined in your apps. The only difference is they’re backed by Realm persistence and abilities. By looking into all Object class Realm are able to infer your schema. Every model you want to persist you have to inherit from Object class.
  2. firstName stores the user first name as String. Since RealmSwift is a wrapper around the Objective-C Realm framework Types like String, Date and Data are sub-classes of NSObject in Objective-C, so you can consider them object types in Swift as well. In addition to this @objc means you want your Swift code (class, method, property, etc.) to be visible from Objective-C whereas dynamic means you want to use Objective-C dynamic dispatch. To make simple swift object stores in database Realm uses Objective-C dynamic dispatch feature to do work under the hood
  3. userId stores the User id which acts as a primary key. You can set one of your object’s properties as its primary key. Usually, property that uniquely identifies itself, that is a prime candidate for a primary key. It helps you a quick lookup or edit object in a database. As shown in Figure 2 we make userId primary key by overriding primarykey static function. The default implementation of this method return nil. Note userId acts as a Objective C primitive Int type since it is a wrapper around Objective C Realm
  4. passport property stores the user passport information which is another Realm Object. We created To-One relationship with the Passport Model. To-one relationship / object link , in which one realm object point to another realm object. When you create a relationship with another Realm object, its property must be of an Optional type. In passport variable pointer reference of Passport object will store
  5. privateUserType is the wrapper property of UserType since UserType is swift enum we can’t store directly on Realm. All of its case values would have an implicitly assigned raw value matching the case’s name. You’ll use this raw value to persist the enum options as Int in Realm. But client is accessing computed enum property and under the hood enum raw value/atomic value is storing in database which is not visible to client.
  6. String, NSDate, and NSData properties can be declared as optional or non-optional using the standard Swift syntax.Optional numeric types are declared using RealmOptional. Since RealmSwift is wrapper around Objective C Realm and there is no optional Int in Objective C that’s why Realm created it’s type RealmOptional for this scenarios. All the Objective C primitive type require in Swift with Optional you have to use RealmOptional . Note: RealmOptional properties cannot be declared as dynamic and @objc keyword because generic properties cannot be represented in the Objective C runtime, which is used for dynamic dispatch of dynamic properties, and should always be declared with let. Since It’s Realm class it has all features that Realm persist object have. As shown in Figure 2 isEmailSubscriptionEnable we declare as RealmOptional Bool means it can be nil we used with let since its a reference type and we don’t want its address to change in future.
  7. As shown in Figure 2 User can have many todos which is a collection of Realm Todo Objects . List as Realm class to hold collection of the Realm Object instances. We created To-Many relationship with the Todo model. To-many relationship , in which one realm object point to collection of realm object. If you use normal Swift array to store Realm collection of Object you will get exception. Note: Like RealmOptional List cannot be declared as dynamic and @objc keyword since its a Realm class with all the built in features. List is very similar to Array for built in methods and accessing objects using indexed subscripting. List as you see is typed and all objects should be of the same type
  8. isUserHasTodos is a computed swift property and will not store in realm database which return if user has some tasks to do or not.
  9. Finally we make userId and firstName as indexed properties. By overriding indexedProperties static method we provide array of properties in String form. We do indexed on properties to improve the access times when filtering or querying the database
Figure 2

Passport Model

  1. passportNumber stores the Passport information and expiryDate stores the expiry date of the passport we want these properties to store that’s why we use @objc with dynamic keyword to tell realm do your under the hood magic
  2. We created passport property on User model which means User object have their passport object reference what if we want passport object also know which user has this passport / have a reference to the user associated with this passport. We created the backlinks using LinkingObjects which means we created ofUser property in Passport that have a reference of all User objects that assign Passport object in its passport property. In Core Data its called it as inverse relationship. Its a dynamic collection telling you who links to the current object.
Figure 3
Figure 4

Add Object to Realm

Figure 5
  1. We get the instance of Realm database
  2. Created Passport and three tasks as a todos
  3. Created User object and assign passport and todos to it. In addition to this initialized Realm optional property which is isEmailSubscriptionEnable and Usertype enum with gold membership
Figure 6
  1. We added User to your Realm, and since it references passport and todos, these objects are also added to the Realm.
  2. By adding unmanaged object to realm we made these objects Managed now as shown in the console our backlinks works. Now passport can access User object as well. Now our database is no more empty
  3. We finally insert object into the database since we are inserting object we have to add in the write transaction block and we add into the realm by using add method on Realm instance. Now If another separate object with the same primary key of User with userId = 1 is attempted to be added as a separate object to the Realm, an exception will be triggered
Figure 7

Check Object Physically Store

Figure 8
Figure 9
Figure 10

Fetch Object from Realm

  1. We get the instance of Realm Database and it can throws: An NSError if the Realm could not be initialized. Default realm is created when we call init() without parameter
  2. Called objects method on Realm database which will return all objects of the given type stored in the Realm and it will return a Results with all the objects as shown in Figure 11
  3. Printed object on console to validate data is there and Linking objects working fine
Figure 11
Figure 12
  1. [==] filter → matches values equal to
  2. [==] [c] filter case insensitive → matches values equal to ignore case
  3. IN {1,2,3} filter → matches value from a list of values.
  4. [BEGINSWITH] filter → matches if the firstName value starts with a.
  5. [CONTAINS] filter → matches if the firstName value conatins with li.
  6. Predicate with Passport object we want to filter User that have passport number == ‘pass1’
  7. Predicate with Todos object we want to filter User that have any tdodo contains details == ‘Need ot create RxSwift blog’
Figure 13
Figure 14

Live results

Figure 15

Modify Object On Realm

Figure 16
Figure 17
Figure 18
Figure 19
  1. We get the User with its primary key userId which is 1
  2. Created new User with the same primary key
  3. On a write transaction we call add batch update method with update = true it will update the User having primary key = 1 . If update = false it will throw an exception since two objects can’t have same primary key as shown in Figure 20 and 21
Figure 20
Figure 21

Delete Object From Realm

Figure 22
Figure 23
Figure 24

Useful Links

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store