I am trying to bulk insert data into Realm, but it is making it very slow.
this is my code:
let realm = try! Realm()
let group = GroupRealm()
group.id = 1
group.name = "test"
try! realm.write {
realm.add(group)
}
var product = [String:AnyObject]()
product["id"] = "" as AnyObject!
product["code"] = ("") as AnyObject!
product["detail"] = ("") as AnyObject!
product["onHand"] = (0) as AnyObject!
product["price"] = (0) as AnyObject!
product["isSerialized"] = (0) as AnyObject!
product["isLotNumber"] = (0) as AnyObject!
var groupProduct = [String:AnyObject]()
groupProduct["group"] = group as AnyObject!
for r in 0..<300 {
realm.beginWrite()
for i in 0..<100 {
product["id"] = "\(i)-\(r)" as AnyObject!
realm.create(ProductRealm.self, value: product, update: true)
groupProduct["id"] = "\(i)-\(r)" as AnyObject!
groupProduct["product"] = product as AnyObject!
realm.create(GroupProductRealm.self, value: groupProduct, update: true)
}
try! realm.commitWrite()
}
The objects I am using are these:
class ProductRealm: Object {
public dynamic var id: String = ""
public dynamic var code: String = ""
public dynamic var detail: String = ""
public dynamic var onHand: Int = 0
public dynamic var price: Double = 0
public dynamic var isSerialized: Int = 0
public dynamic var isLotNumber: Int = 0
override static func primaryKey() -> String? {
return "id"
}
}
class GroupProductRealm: Object {
public dynamic var id = ""
public dynamic var group: GroupRealm!
public dynamic var product: ProductRealm!
override static func primaryKey() -> String? {
return "id"
}
}
class GroupRealm: Object {
public dynamic var id = 1
public dynamic var name = ""
public dynamic var update = Date()
override static func primaryKey() -> String? {
return "id"
}
}
Testing on my iphone 5s to insert 30000 records takes over 30 seconds, while on an old project I have with sqlite it takes around 16 seconds.
I've read that realm is much faster at this than sqlite, so I know it's my mistake, but I can't find the D: