Using Realm Mobile Database with Swift 4.0 (Insert, Update, Delete, List)
A big problem that many developers face now a days is dealing with database. To have your app in app store in top list is not quite easy and to make the app ready for scalability is pretty hard. When our app is reached to many users, say a million, we have to care about everything in the app from performance to scalability. As far as I see till date developers have only two options “SQLite” and “Core Data”. Though both have a lot of advantages over each, I love to work with “Core Data” because of ease of dealing with records and persisting data and also due to the native advantages of “Core Data”. Very Recently I started using Realm that can be considered as a perfect replacement for “SQLite” and “Core Data”.
What is Realm?
Realm, it’s a cross platform mobile database for iOS and Android and designed specifically for mobile applications. It is available in both Swift and Objective-C. It is framed to be faster and better than SQLite and CoreData. With just few lines of code a lot of things can be done better and faster. Realm uses its own persistence engine to achieve the better performance and speed.
1. Light weight and simple to integrate in our project.
2. Better and faster than even raw SQLite on common operations.
3. Automatic and seamless realtime data sync.
4. Supports relationships, generics, vectorization and Swift.
Let’s get started…
Let’s get started building simple iPhone app with Swift and Realm. The sample application is just list of users. User can add users with Name and address. Before starting, we need to configure the Xcode and install the tools needed to work with Realm.
Xcode 6.3 or later.
Realm for Swift.
1. Before proceeding for building an app, please make sure that you have CocoaPods installed. We use CocoaPods for installing Realm in the Xcode project. Several online tutorials can be found to know about CocoaPods.
2. Create a “Single View Application” Xcode project and name it as “RealmSample” or anything you prefer. Make sure Swift is selected as a programming language.
3. Open terminal and navigate to your project directory. Here we configure the CocoaPods. Run the following command in terminal to initialize CocoaPods: $pod init
4. Open the pod file generated with XCode and add pod 'RealmSwift’,'~>2.7.0’ after your target. The file should look like below
5. Close the pod file and run the command “pod install” in the terminal to download and install the Realm in your project. 6. Once done, we see a new Xcode workspace has been generated with the project name as RealmSample.xcworkspace. 7. Open .xcworkspace file instead of .xcodeproj. Once you open the workspace, you will see something like below: 8. Open AppDelegate.swift and add the following lines marked in the boxes.9. Our sample is to create the list of users with their general data like first name, lastname, age and gender. Later show the list of users and edit the details of selected user. 10. Let’s create the object classes for the users. Let’s name it as person.swift and have the respective variable define. As below:
A RealmOptional instance represents an optional value for types that can't be directly declared as 'dynamic' in Swift, such as 'Int', 'Float', 'Double', and 'Bool'. To change the underlying value stored by a 'RealmOptional' instance, mutate the instance's 'value' property.
11. Let’s create a “RealmManager.swift” class which will manage the database methods like save objects, edit objects, get objects and delete objects. We mainly concentrate on
Add, Edit, Get, Delete and Lists in Realm.
Add (same as insert query)-> realm?.add(objs, update: false)
Edit (same as update query)-> realm?.add(objs, update: true)
Get (same as select query) -> realm!.objects(type)
Delete (same as delete query) -> realm?.delete(objs)
Delete Total Database -> realm?.deleteAll()
All the above actions should be performed in the try block and we need to check if the database has the write permissions. It can be done by doing
Adding Details to Database:
12. Create a “AddViewController.swift” class with a simple UI of 4 text fields which represent first name, last name, age and gender and a Save button to save the data in the database. 13. Define the method for Save button to save the person data and add the following code. We can use the same class to edit and add the details. As of now let’s talk about saving the new objects into the database. In the above method you can observe the method saveObjects() method defined in RealmManager.swift which uses realm.add() method with the object to be saved and the update parameter set to false, which implies that new object has to be added to the database. Retrieve the data from database and display in the tableView 14. Create a class with list view to display the list of persons added retrieving from database. Let’s say the class name as “ViewController.swift” and add the UITableview to display the list of users. 15. Define an array of type Persons.swift (the object class we created earlier) and add the person objects to that array. In ViewWillAppear we can define an array “personsArr” of type Person and then call the function “getAllObjects()” which will in-turn call the “getObjects()” from RealmManager.Swift. This will give the persons data stored in database and will reload the tableView. In RealmManager.swift , getObjects(type:) method will return the objects of type person that we had invoked from ViewController.Swift class. We parse those objects and will be loading in the tableview using respective datasource and delegate methods.
“realm!objects(type)” this will get the objects of the typed defined. This is something like the “select * from <table>” query in the regular SQLite.
Get the details of selected person from the List view and Edit the details:
Once we load the person details in “ViewController.swift”, we can select the specific user from tableview “didSelectRow” method and navigate to “AddViewController.swift”. We use the same class for both adding and editing the details. From here we populate the selected person details in the textfields. We will have the selected person details with the personArr we had added the persons objects at while retrieving the data.
After changing any of the details, you can save the details. Depending on the boolean variable “isEditingData” (the variable we use to differentiate to add or edit the details), we pass the edited data to the “editObjects()” method in “RealmManager.swift” class.
In RealmManager.swift, add the following the lines of code to edit the details in database
The above method will be very similar to the realm.add(), the only difference is we specify the update parameter to true which will specify that the object need to updated in database.
In “ViewController.swift”, enable tableview editing to true and add the following lines of code.
The realm?.delete(objs) will delete the given object from database.
List is the container type in Realm used to define to-many relationships.Like Swift’s Array, List is a generic type that is parameterized on the type of Object it stores.Unlike Swift’s native collections, Lists are reference types, and are only immutable if the Realm that manages them is opened as read-only.Lists can be filtered and sorted with the same predicates as Results<Element>.Properties of List type defined on Object subclasses must be declared as let and cannot be dynamic.
To check with an example
Create the object class Task.swift and add the following lines of code
And then create another object class TaskList.swift which will accepts the List type of object.
Create a TasksViewController.swift to create the tasks and add that tasks as List and try to add them in the database.
Get Realm File to check the database. To get the path of the file you can write the following code in any swift class and run the app on simulator
Navigate to that file path, you can see default.realm database file. Install Realm Browser to open that file and you can see something like below and you can observer how tasks are saved as List in tasklist table.
Note: After downloading the code, please do run $pod install command from terminal in the project folder path which will create the .xcworkspace file. Open that file to run the code.
Why Swift Code Application Programming Language is the Best?
Swift may be considered a young platform in the development world. But, it has surely paved its way to becoming the most sought after language...
Why iPhones and iPads are Currently Ruling the Smartphone Industry
iPhone is a pioneer in the smartphone industry as it was developed much before the Android devices. First iPhone was launched on June 29, 2007...