Greetings Humans!
I was thinking for a long time to write about Realm. So…
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.
Create a project and initiate a pod in it, then open the pod file and paste the following snippet in it.
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.
I have made a View Controller and created all the outlets and actions of the views on it.
Additionally, I also have created a Model class which in other words you can say table. With id as the primary key.
import UIKit import RealmSwift class Model: Object { dynamic var name : String? dynamic var id : String? override class func primaryKey() -> String? { return "id" } }
Now, open your ViewController class and add two variables to it.
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.
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.
//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.
//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 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.
//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 is pretty straight forward. Check if the object exists in realm, then inside write block delete it from realm.
//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() } }
In datasource functions of the tableview.
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!
This article covers some important things you must know when you are considering a move…
What is Unit Testing? In its simplest term, unit testing is testing a small piece…
In this article, you will learn about a type of Creational Design Pattern which is…
In this tutorial, you will go through the use of targets to achieve two separate…
In this article, you will learn about a type of Structural Design Pattern which is…
In this article you will learn about a type of Creational Design Pattern which is…
View Comments
Great effort, its amiazing!!!
Great !!
Great Tutorial!
I found many tutorial about using Realm but most of them is making simple ToDo app and just use the add object function. You have done good job.
Beside, if I were you, I would code a little different in some points:
1. No need to put conditions in brackets ()
2. I avoid calling self if not necessary (only in closure and initialiser if needed)
3. Function returns a boolean should be named started with "is", let say, in my code
func isTextFieldEmpty() -> Bool {
if nameTextField.text == "" || idTextField.text == "" {
// And return TRUE if they are really empty (not false like yours)
return true
}
return false
}
it's like normal English and we can call these condition by: if !isTextFieldEmpty {}
4. In updateButtonTapped action, why we have to initialise an model object, then set its property according to object, then assign the object = model, then update the object to realm instead of doing like this:
try! realm.write {
object!.name = nameTextField.text
realm.add(object!, update: true)
Thanks
Hi QuocLoi. I will keep these things in mind from next time. Thanks.