Created
June 19, 2020 10:29
-
-
Save chaitanyaSoni96/fb89edf947218c74981de9bef0bfdce1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can make a deep copy of your object via the following extension functions: | |
import UIKit | |
import Realm | |
import RealmSwift | |
protocol RealmListDetachable { | |
func detached() -> Self | |
} | |
extension List: RealmListDetachable where Element: Object { | |
func detached() -> List<Element> { | |
let detached = self.detached | |
let result = List<Element>() | |
result.append(objectsIn: detached) | |
return result | |
} | |
} | |
@objc extension Object { | |
public func detached() -> Self { | |
let detached = type(of: self).init() | |
for property in objectSchema.properties { | |
guard let value = value(forKey: property.name) else { continue } | |
if let detachable = value as? Object { | |
detached.setValue(detachable.detached(), forKey: property.name) | |
} else if let list = value as? RealmListDetachable { | |
detached.setValue(list.detached(), forKey: property.name) | |
} else { | |
detached.setValue(value, forKey: property.name) | |
} | |
} | |
return detached | |
} | |
} | |
extension Sequence where Iterator.Element: Object { | |
public var detached: [Element] { | |
return self.map({ $0.detached() }) | |
} | |
} | |
Use | |
/// in collections | |
let data = realm.objects(AbcDfg.self).detached | |
/// single object | |
data.first?.detached() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment