Realm database: Replacing SQLite & Core Data Part 1 to 2
This is the first post of a 2 series about Realm database (Using Swift).
This article starts from the beginning of making new project and it assumes that the reader has little knowledge already from the Xcode and Swift.
What is Realm?
The core concept of the Realm Mobile Platform is a lightweight object container called a Realm. Like a database, data in Realms can be queried and filtered, interconnected, and persisted. Unlike a traditional database, though, objects in Realms are live and fully reactive. Realms synchronize seamlessly between devices and applications, and can be accessed safely across threads.
Realm is a cross-platform mobile database designed specifically for mobile applications. It’s lightweight and very simple to integrate in your project.
Realm Mobile Database is the best alternative to SQLite and Core Data. Thanks to its zero-copy design, Realm Mobile Database is much faster than an ORM, and often faster than raw SQLite. Get started in minutes, not hours. Realm is the best choice for your mobile database. It delivers automatic and seamless realtime data sync and powerful event handling between server and devices. You never need to think about networking code again.
The Realm Mobile Database is cross-platform, supporting both iOS and Android, and the Realm Object Server is ready to run on your servers or on your favorite cloud.
The Realm Mobile Database is available for Android (Java), iOS (Objective-C and Swift), Xamarin, React Native, and Node.js.
What does it?
In order to better understand what Realm does, here’s an overview of the Realm classes and concepts you’ll use in this tutorial:
Realm: Realm instances are the heart of the framework; it’s your access point to the underlying database, similar to a Core Data managed object context. You will create instances using the
Object: This is your Realm model. The act of creating a model defines the schema of the database; to create a model you simply subclass
Object and define the fields you want to persist as properties.
Relationships: You create one-to-many relationships between objects by simply declaring a property of the type of the
Object you want to refer to. You can create many-to-one and many-to-many relationships via a property of type
List, which leads you to…
Write Transactions: Any operations in the database such as creating, editing, or deleting objects must be performed within writes which are done by calling
Queries: To retrieve objects from the database you’ll need to use queries. The simplest form of a query is calling
objects() on a
Realm instance, passing in the class of the
Object you are looking for. If your data retrieval needs are more complex you can make use of predicates, chain your queries, and order your results as well.
Results: Results is an auto updating container type that you get back from object queries. They have a lot of similarities with regular
Arrays, including the subscript syntax for grabbing an item at an index.
Let’s get started with Realm tutorial and use it to build a simple iPhone app with Swift. The demo project will be a simple Todo application. User can add Task Lists and each list can contain multiple tasks. The task has a title, notes, due date, attachment image. Before starting with Xcode project. We need to first configure Xcode and install the tools needed to work with Realm.
First, install the MacOS bundle if you haven’t yet. This will get you set up with the Realm Mobile Platform and let you launch the macOS version of RealmTasks.
Please consider the following prerequisites:
- iOS 8 or later, OS X 10.9 or later.
- Xcode 7 or later.
- I recommend using Realm for Swift 3.0.
Configuring Tools needed and Xcode
Before configuring the Xcode project, please make sure that you have installed CocoaPods in your computer as we’ll use it for installing Realm in the Xcode project. If you aren’t familiar with CocoaPods, you can check online for several tutorials to give you all information you need for getting started with it.
Ok, now you should to create a new Xcode project with the template “Single View application” and named it “Todo-List” or whatever you want.
Please make sure that you selected “Swift” as a programming language.
Open the terminal and navigate to directory where the project was created and type the following:
Then open the pod file generated with Xcode and edit it to add pod ‘RealmSwift’ right after your target, so it should be something like this:
Next run the command “pod install” in your terminal to download the install Realm in your project. After finishing, you’ll see a new Xcode workspace has been generate beside your project file. Please open the workspace Todo-List.xcworkspace and don’t open the xcodeproj. After you open the workspace, you should see something like this:
Now Xcode is ready to work with Realm, but we’ll install the following tools to make things easier while working with Realm.
Installing Realm plugin in Xcode
Realm team has provided a very useful plugin for Xcode that will be used for generating Realm models.
The one tool I want to mention is Realm browser. This browser helps you to read and edit your .realm databases files. These files are created in your app with all information about entities, attributes and records inside database tables. I said before that these files can be shared among different platform like iOS or Android. To download the realm browser tool please visit iTunes store to download the latest version. Open the app then choose Tools -> Generate demo database. It will generate test database realm file to you and you can open it and see its content with the browser. You should see something like this when you open your demo database:
Now we have everything that needed for working with Realm database , let’s go!
Database Model Classes
Now game on! First I’ll create the model classes for our database. To create Realm model classes, you simply create normal Swift classes that extend the Object class. Think of Object as the base class for all Realm model classes, as well you can extend any class that extend Object at the end. Once you create your class, of course you need properties. Realm supports variety types of properties as follows:
– Int, Int8, Int16, Int32, and Int64
– Class extends Object => Used for One-to-one relations
– List<Object> => Used for one-to-many relations
Remove parts of the Xcode project to start with a simple base
- Delete the
Main.storyboardfile from the Xcode project navigator, clicking “Move To Trash” when prompted.
- On the “General” tab of the
Todo-Listtarget editor, clear the “Main Interface” text field in the “Deployment Info” section.
- Also on the “General” tab, enter an organization name and select a team name (you may need to log in to your Apple developer account via Xcode’s Preferences/Account pane)
- Switch to the “Capabilities” tab and turn on the “Keychain Sharing” switch.
Delete the contents of the
ViewController.swift file, replacing it with this:
Now replace the contents of
AppDelegate.swift with the following:
Your app should now build and run (so far it will just show a blank screen).
Go to Xcode project, open the Todo-List folder and create a subfolder named “Models” (right-click on project and choose “New group” option). After, right-click on Models folder and choose “New File” option, you should to see the following screen:
Choosing the “Swift File” option, type “Task” as name file. You should to see the recent file created:
Please, open the Task.swift file, delete everything and type inside that the following:
Ok now create a new file named “TaskList” and type the following:
Add a title and register a cell class for use with our table view
Add the following to the body of your
Now, run your app, you should to see a screen like:
In my second post about that I’ll write of how persist data using Realm.