This time: how to add Swift Realm to an iOS app.
What is Swift Realm?
Realm is an embedded database for mobile apps.
It works on both iOS and Android.
On iOS there are Objective-C and Swift versions — the Swift version is Swift Realm.
Unlike a traditional DB, there's no SQL or advanced query language.
Instead, class member variables map directly to DB columns,
and objects represent DB records.
This means you define the DB schema through class definitions,
and object operations become record operations —
no database knowledge required.
If that paragraph made zero sense to you, don't worry — just keep reading.
CocoaPods
Before adding Swift Realm, first install CocoaPods.
CocoaPods is a library/dependency manager for Mac.
Open Terminal on your Mac and run the following commands in order:
1. Update Ruby
2. Install CocoaPods
3. Initialize CocoaPods
$ sudo gem update --system
$ sudo gem install cocoapods
$ pod setup
That's it.
Installing Swift Realm
Now add Swift Realm to your project.
First, navigate to your Xcode project folder.
For example, if you have a project called "ProjectName" on the Desktop:
$ cd ~/Desktop/ProjectName/
Create an empty Podfile:
$ pod init
A file called Podfile is created. Edit it to add the dependencies:
$ vi Podfile
Quick vim reference: k/j/h/l to move the cursor up/down/left/right.
Press i to enter insert mode.
Press ESC to exit insert mode, then :wq to save and quit.
(Technically :w saves and :q quits.)
target 'ProjectName' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for ProjectName
pod 'Realm'
pod 'RealmSwift'
Then install:
$ pod install
On success, a workspace file will be created in your project folder.
If you have the .xcodeproj file open in Xcode, close it
and reopen the workspace file (.xcworkspace) instead.
A Pods project should appear in the workspace, with Realm installed.
In Xcode's file tree, click your project name.
Under TARGETS, click your project name.
At the bottom of the General tab, find "Linked Frameworks and Libraries" and add Realm.framework.
Try building — if it compiles without errors, the installation is complete.
Side note: vim is a lightweight command-line editor.
It has a steep learning curve, but once you know it,
features like regex-based bulk replace and block copy-paste make it far more powerful than a normal editor.
Once you get used to vim, clicking around with a mouse starts to feel unbearably slow.
Using Swift Realm
In Swift Realm, one table = one class.
Let's create a file called SampleDB.swift as a test:
import Foundation
import RealmSwift
class Sample : Object {
dynamic var id:Int = 0
dynamic var name:String = ""
dynamic var password:String = ""
override static func primaryKey() -> String? {
return "id"
}
override static func indexedProperties() -> [String] {
return ["id","name","password"]
}
}
class SampleDB {
var realm = SampleDB.getRealm()
static func getRealm() -> Realm {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let realmPath = (paths[0] as NSString).appendingPathComponent("sample.realm")
let realmURL = URL(fileURLWithPath: realmPath)
return try! Realm(fileURL: realmURL)
}
}
The Sample class defines the DB table structure.
In this example, there are three columns: "id (Int)", "name (String)", and "password (String)".
SampleDB is the DB access class.
Keeping the Realm object as a static member makes things simpler.
Inside getRealm(), you could technically just write return try! Realm().
However, that limits you to the table defined in the Sample class.
Using Realm(fileURL:) lets you reference any Realm file you specify.
In this example, it uses a file called "sample.realm".
This approach lets you create multiple DB access classes,
each with its own table structure.
From here, add methods to SampleDB to insert and query records via the realm object.
Accessing Realm
Realm access must happen on the main thread.
For example, inserting a record looks like this:
func append( item:Sample ) {
DispatchQueue.main.async {
try! self.realm.write() {
self.realm.add(item, update: true) // insert if new, update if exists
}
}
}
Passing update: true to add() gives UPSERT behavior (insert or update).
For everything else, the official Realm documentation has detailed explanations with sample code.
No comments:
Post a Comment