0

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 e.g:

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?

Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
Martin
  • 1,135
  • 1
  • 8
  • 19

2 Answers2

4

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() }
}
pacification
  • 5,838
  • 4
  • 29
  • 51
0

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.

christopher.online
  • 2,614
  • 3
  • 28
  • 52
  • Your code will not compile because of optional self. The note about `!` is good (describing [here](https://realm.io/docs/swift/latest/#writes): _For brevity, our code samples don’t handle these errors, but you certainly should in your production applications._) – pacification Jan 25 '18 at 06:10
  • 1
    @pacification thanks for the comment, fixed the code – christopher.online Jan 25 '18 at 08:04