Reputation: 259
I started trying Realm for IOS, so I created two classes:
Files Model
import Foundation
import RealmSwift
class FilesModel: Object {
@objc dynamic var id : Int = 0
@objc var fileName = ""
@objc dynamic var dateOfCreation = Date()
@objc dynamic var dateOfModification = Date()
@objc dynamic var type = ""
var file = List<Data>()
}
Groups Model
import Foundation
import RealmSwift
class GroupsModel: Object {
@objc dynamic var id : Int = 0
@objc dynamic var name = ""
@objc dynamic var dateOfCreation = Date()
@objc dynamic var dateOfModification = Date()
@objc dynamic var filesCount = Int()
var files = List<FilesModel>()
override static func primaryKey() -> String? {
return "id"
}
}
Now the thing is I am copying files into groups model file Object but I need to delete the parent object. think of it as a move I am moving files into the folder. what I have done is I save a copy of the file into the folder and delete the file from outside the folder.
Problem
when I delete the file outside the folder it will also delete the file inside.
My understanding of the problem
classes is a reference type so I am copying reference. So when I delete the reference it will delete the file from the whole project.
I have tried many solutions like deep copy and detached. Thanks in Advance.
Upvotes: 0
Views: 270
Reputation: 35648
The issue is this statement
I am moving files into the folder
While that may be what you want to do, the objects you're moving aren't actually being moved. When you add a managed object to a a List property, it adds a reference to the object, not the object itself.
In other words, when a FilesModel is added to a GroupsModel files List property, it's a reference to the object. If you delete the FilesModel, it will also be gone from the List. But, removing it from the List does not change the original object.
However, Lists can also contain Embedded Objects - an embedded object only ever exists within it's parent object. Perhaps that would be an option?
So like this. Here's a couple of models
class FileModel: EmbeddedObject {
@Persisted var fileName = ""
}
class GroupsModel: Object {
@Persisted var files = List<FilesModel>()
}
Then instantiate a group and add a couple of file objects to it
let group = GroupsModel()
let f0 = FileModel()
f0.fileName = "some filename"
let f1 = FileModel()
f1.fileName = "another filename"
group.files.append(objectsIn: [f0, f1])
results in a group with two files that only ever appear within that group.
Another option is to simply make a copy of the object
let objectCopy = MyObject(value: objectToCopy)
and then add the objectCopy to your Groups model. But again, by doing that Realm will instantiate the objectCopy and actually add it back to Realm (possibly overwriting the original object).
Upvotes: 2