Richard Topchii
Richard Topchii

Reputation: 8165

iOS + React Native - memory leaks

I'm considering making an iOS project in React Native. On iOS it's a big issue to find and fix so-called "retain cycles", i.e. when the two object store a strong reference to each other:

class Obj1 {
    var delegate: Obj2?
}

class Obj2 {
    var delegate: Obj1?
}


let obj1 = Obj1()
let obj2 = Obj2()

obj1.delegate = obj2
obj2.delegate = obj1

Does the React Native has a concept of a memory leak or retain cycle? Would the similar code in the JS counterpart create a retain cycle in React Native environment?

How about passing a closure capturing self? Would that also create a memory leak in React Native?

Summary:

  1. Would the listed sample code (rewritten to JS) cause a memory leak in RN?
  2. Would capturing self in a closure cause a memory leak?

Upvotes: 0

Views: 725

Answers (1)

Adis
Adis

Reputation: 4552

You shouldn't really have two objects retaining strong references to each other, the delegate pattern is usually handled by having one strong and one weak reference, where the delegate is the weak one.

Now onto your questions:

  1. Probably, but someone else might give you a better answer since I'm not entirely sure about RN.

  2. Yes and no, depending on how you go about it.

If you use strong self, then definitely there will be a memory leak:

{ _ in
    self.doSomething()
}

Better way is to use either weak self:

{ [weak self] _ in
    guard let self = self else { return }
    self.doSomething()
}

or unowned self if you can guarantee self is available in the closure at all times:

{ [unowned self] _ in
    self.doSomething()
}

Upvotes: 0

Related Questions