Realm Updated Tutorial
Realm Updated Tutorial
?
1 platform :ios, ‘9.0’
use_frameworks!
2
3
source 'https://github.com/CocoaPods/Specs.git'
4
5
target 'MyApp' do
6 pod 'RealmSwift'
7 end
1
2 import RealmSwift
3
4 class Person: Object {
5
6 private(set) dynamic var id = 0
private(set) dynamic var name = ""
7 private(set) dynamic var email = ""
8
9 /**
10 Override Object.primaryKey() to set the model’s primary key. Declaring a primary
11value.
*/
12 override static func primaryKey() -> String? {
13 return "id"
14 }
15
16 convenience init(id: Int, name: String, email: String) {
17 self.init()
18
self.id = id
19 self.name = name
20 self.email = email
21 }
22}
23
Also, we need a RealmManager class to manage the realm
operations, like delete, save, get and so on. For a brief presentation, I've
added only the following three methods:
?
1
2
3 import RealmSwift
4
5 class RealmManager {
6
7 let realm = try! Realm()
8
9 /**
Delete local database
10
*/
11 func deleteDatabase() {
12 try! realm.write({
13 realm.deleteAll()
14 })
}
15
16 /**
17 Save array of objects to database
18 */
19 func saveObjects(objs: [Object]) {
20 try! realm.write({
// If update = true, objects that are already in the Realm will be
21 // updated instead of added a new.
22 realm.add(objs, update: true)
23 })
24 }
25
26 /**
Returs an array as Results<object>?
27 */
28 func getObjects(type: Object.Type) -> Results<object>? {
29 return realm.objects(type)
30 }
}</object></object>
31
32
33
You can notice that when we save in the realm database, we don't need to
specify the object type, but when we retrieve the objects we need to specify
the object meta type that we want to be retrieved.