2

I just want to use function parameter inside swift closure without memory leak, so I just want to confirm if I do in following way will there be any memory related issues? Kindly let me know

func someMethod(someValue: String) {
    weak var weakSelf = self
    var copyOfSomeValue: String? = someValue.copy() as? String
    self.someOtherMethodWithCompletion(completionHandler: { () -> Void in
        if let strongSelf = weakSelf, let originalValue = copyOfSomeValue {
            strongSelf.updateMyViewWithText(originalValue)
        }
    })
}
nhgrif
  • 61,578
  • 25
  • 134
  • 173
Vignesh
  • 3,571
  • 6
  • 28
  • 44

2 Answers2

1

With swift you should use [unowned self] and just use swift as normal, for example:

func someMethod(someValue: String) {
    var copyOfSomeValue: String? = someValue.copy() as? String
    self.someOtherMethodWithCompletion(completionHandler: { () ->
        [unowned self]
         in
        if let originalValue = copyOfSomeValue {
            self.updateMyViewWithText(originalValue)
        }
    })
}

You should use weak or unowned just to variables which can cause reference cycle. The difference between those is:

Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization

Greg
  • 25,317
  • 6
  • 53
  • 62
1

String is a value type. Even though closures capture them by reference, there is no need to make a copy unless you are going to change someValue after the capture. Even then you're better off using capture lists [someValue], which are also used when you need to declare [weak self].

Using weak or unowned is situational, read about them here.

func someMethod(someValue: String) {
    someOtherMethodWithCompletion { [weak self] in
        self?.updateMyViewWithText(someValue)
    }
}
Community
  • 1
  • 1
Nikita Kukushkin
  • 14,648
  • 4
  • 37
  • 45