[英]Should l I use [unowned self] for Realm.write()?
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: 我使用Realm并有例如:
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. 如果看一下write
方法声明,您会发现闭包是不可逃避的。 So, you don't need to use neither weak
nor unowned
. 因此,您既不需要使用weak
也可以使用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. 如果不了解领域,我建议您使用weak self
,以防自我可能为零。
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. 尝试部分,而是正确处理可能的错误情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.