This question is about using two different ways to insert objects into a Realm. I noticed that the first method is a lot faster,
but the size result is huge comparing with the second method. The diference between the two approaches is moving the
write transaction outside vs inside of the for
loop.
// Create realm file
let realm = try! Realm(fileURL: banco_url!)
When I add objects like this, the Realm file grows to 75.5MB:
try! realm.write {
for i in 1...40000 {
let new_realm_obj = realm_obj(value: ["id" : incrementID(),
"a": "123",
"b": 12.12,
"c": 66,
"d": 13.13,
"e": 0.6,
"f": "01100110",
"g": DateTime,
"h": 3])
realm.add(new_realm_obj)
print("?? (i) Added")
}
}
When I add objects like this, the Realm file only grows to 5.5MB:
for i in 1...40000 {
let new_realm_obj = realm_obj(value: ["id" : incrementID(),
"a": "123",
"b": 12.12,
"c": 66,
"d": 13.13,
"e": 0.6,
"f": "01100110",
"g": DateTime,
"h": 3])
try! realm.write {
realm.add(new_realm_obj)
print("?? (i) Added")
}
}
My Class to add to realm file
class realm_obj: Object {
dynamic var id = Int()
dynamic var a = ""
dynamic var b = 0.0
dynamic var c = Int8()
dynamic var d = 0.0
dynamic var e = 0.0
dynamic var f = ""
dynamic var g = Date()
dynamic var h = Int8()
}
Auto increment function
func incrementID() -> Int {
let realm = try! Realm(fileURL: banco_url!)
return (realm.objects(realm_obj.self).max(ofProperty: "id") as Int? ?? 0) + 1
}
Is there a better or correct way to do this? Why do I get such different file sizes in these cases?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…