I have some weird memory issues in an app and I'm wondering if I'm doing the correct thing here. I use Realm and have eg:
try! self.realm.write {
self.realm.add(newItem)
}
But I'm wondering if I'm causing a retain cycle inadvertently so should maybe do:
try! self.realm.write { [unowned self] in
self.realm.add(newItem)
}
Which would be correct and why?
If you have a look at the write
method declaration, you will see, that the closure is non escaping. So, you don't need to use neither weak
nor unowned
. It will not lead to retain cycle.
public func write(_ block: (() throws -> Void)) throws {
beginWrite()
do {
try block()
} catch let error {
if isInWriteTransaction { cancelWrite() }
throw error
}
if isInWriteTransaction { try commitWrite() }
}
Without knowing much about realm I would suggest using weak self
in case that self might be nil.
try! self.realm.write { [weak self] in
self?.realm.add(newItem)
}
and maybe try to avoid using !
for the try part and instead handle a possible error case properly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.