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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
target 'YourProjectName' do use_frameworks! pod ‘RealmSwift’ end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '3.0' end end end |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import UIKit import RealmSwift class Model: Object { dynamic var name : String? dynamic var id : String? override class func primaryKey() -> String? { return "id" } } |
Adding Object to Realm
Now, open your ViewController class and add two variables to it.
1 2 |
var model : Model? let realm = try! Realm() |
We are going to create a function to check if Realm already contains the primary key we are trying to add in.
1 2 3 4 5 6 7 8 9 10 11 |
func ifIdExists(findID: String) -> Model?{ let predicate = NSPredicate(format: "id = %@", findID) let object = self.realm.objects(Model.self).filter(predicate).first if object?.id == findID { return object } return nil } |
I have also created some helper functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
//Checks if both fields are empty func checkIfEmpty()-> Bool{ if (nameTextField.text == "" || idTextField.text == ""){ return false } return true } //Checks if Id field is empty func checkIfIdIsEmpty()-> Bool{ if (idTextField.text == ""){ return false } return true } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//Inside done button action if checkIfEmpty(){ //Initialize Model object self.model = Model() //Set properties in it model!.name = self.nameTextField.text! model!.id = self.idTextField.text! if let data = model{ //Check if the entered 'id' is not already present if self.ifIdExists(findID: idTextField.text!) == nil { try! self.realm.write { //Add object to Realm self.realm.add(data) //Refresh UI self.tableView.reloadData() } } } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//Inside Update button action if checkIfEmpty(){ //Check if object we want to change exists or not var object = self.ifIdExists(findID: self.idTextField.text!) if (object != nil){ //If yes try! self.realm.write { self.model = Model() //Update object model!.name = self.nameTextField.text //Leave the primary key same model!.id = object!.id! object = self.model self.realm.add(object!, update: true) self.tableView.reloadData() } } } |
Deleting Object from Realm
Deleting is pretty straight forward. Check if the object exists in realm, then inside write block delete it from realm.
1 2 3 4 5 6 7 8 9 |
//Inside Delete button action if self.checkIfIdIsEmpty(){ let objectToDelete = self.ifIdExists(findID: idTextField.text!) if objectToDelete != nil{ try! realm.write{ realm.delete(objectToDelete!) self.tableView.reloadData() } } |
Displaying on TableView
In datasource functions of the tableview.
1 2 3 4 5 6 7 8 9 10 11 |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let model = self.realm.objects(Model.self)[indexPath.row] cell.textLabel!.text = model.name! cell.detailTextLabel!.text = "ID: \(model.id!)" return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return realm.objects(Model.self).count } |
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