是否可以将一组对象保存到Realm?每当我对数组进行更改时,都应将其保存到Realm.
我目前的解决方案是使用for循环保存对象的对象.对于追加/修改对象,调用save()将完成工作,但是当我从中删除对象时不会.
class CustomObject: Object { dynamic var name = "" dynamic var id = 0 override static func primaryKey() -> String? { return "id" } } struct RealmDatabase { static var sharedInstance = RealmDatabase() var realm: Realm! let object0 = CustomObject() let object1 = CustomObject() var array = [object0,object1] init() { self.realm = try! Realm() } func save() { for object in self.array { try! self.realm.write { self.realm.add(object,update: true) } } } }
要保存对象列表,必须使用Realm List,而不是Swift Array.
原文链接:https://www.f2er.com/swift/318606.htmllet objects = List<CustomObject>()
然后,您可以添加元素:
objects.append(object1)