This repo covers a basic ready-to-go implementation of RealmSwift in the iOS-starter-kit.
The main purpose is to offer a fast -yet efficient- implementation of the persistance feature in the starter kit; for any further information, please check the official Realm Documentation.
This 3-min installation is made for the release 1.5.0
of the starter kit.
-
Add
pod 'RealmSwift','~> 3.3.1'
in your Podfile and make the magic happen (pod install
) -
Examples files are inside the
Examples
folder,1- Copy all functions from
DataManager
in yourDataManager
.2- In Xcode, go to
starterkit/core/data/provider/
, right-click onprovider
andAdd files to "starterkit"
3- Add the complete
realm
folder fromExamples
. TickCreate groups
(instead ofCreate reference
). IfCreate groups
is not visible, click onOptions
at the bottom. -
All files are added, your starter-kit now supports persistance. At this point, it will try getting data from the cache; if empty, it will try fetching data from the database and store it in the cache; if empty, fetch data from the network and store it in both cache and database.
From now on you are ready to go.
TO GO FURTHER
- DataManager
- Realm
- RProvider
- mapper
- ItemRMapper
- dto
- ItemRDto
R will now stand for Realm, AF for Alamofire. ItemDto :
ItemRDto
/ItemAFDto
It will show you the implementation for fetching / saving and clearing data.
Models will be persisted as DTOs.
Persisting objects (DTOs) must subclass
Object
Realm model properties must have the
@objc dynamic var
attribute to become accessors for the underlying database data.
Please refer to this Realm property cheatsheet.
let itemRDtos = realm.objects(ItemRDto.self) //this will not load the fetched objects into memory
All queries (including queries and property access) are lazy in Realm. Data is only read when the properties are accessed.
Please check the NSPredicate Cheatsheet for the predicate string syntax.
var filteredItemRDtos = itemRDtos.filter("title = 'example' AND description BEGINSWITH 'I'")
var sortedItemRDtos = itemRDtos.sorted(byKeyPath: "title", ascending: true)
- Always set a primary key for any DTO model you are going to use.
override static func primaryKey() -> String? {
return "id"
}
Realm will update the existing stored data with the new ones by looking for its primary key.
Without this, you will have to delete all the persisted data and then persist the new ones; huge performance costs.
- Always force
update: true
when updating/saving persisted data.
try realm.write {
realm.add(dto, update: true)
}
This will update existing dto
objects in the database, looked up by its primary key. If it does not exist, it will be created and added to the database.
- Delete the Realm file from disk
do {
try FileManager.default.removeItem(at: Realm.Configuration.defaultConfiguration.fileURL!)
} catch {}