Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would it cause retain cycle that add a subview on a view passed by parameter of a function?

For example:

// CustomViewClass

- (void)showOnView: (UIView*)view {
    [view addSubview: self.customView];
}

Then invoke this method at another class, like a view controller's viewDidLoad.

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.customViewClass showOnView: self.view];
}

I pass a view controller's view to CustomViewClass as the above.

My question is: Would it cause some kind of retain cycle?

Are these views passed through parameter referenced weakly?
Or it's fine to that.

It would be highly appreciated if anyone explain it in both Swift and Objective-C.

like image 549
JsW Avatar asked Jun 15 '18 11:06

JsW


2 Answers

What is Retain Cycle? - It's the condition when 2 objects keep a reference to each other and are retained, it creates a retain cycle since both objects try to retain each other, making it impossible to release.

In this case, self.customViewClass keep a reference to self.view but self.view doesn't keep any reference to self.customViewClass. Which keeps reference to self.customViewClass is self, not self.view.

So of course, it won't causes retain cycle

Don't believe in me ? 🤣 - Check it yourself by trying to log something inside dealloc method.

After you dismiss CustomViewController, if the code inside dealloc is called and log something, it means no retain cycle here. If not, it causes retain cycle.

For example

- (void)dealloc {
  NSLog(@"BOOM RIGHT ANSWER!!!");
}
like image 89
trungduc Avatar answered Nov 15 '22 03:11

trungduc


Memory leaks happens when two class having objects pointing to each other .For e.g.

 class A{
   var object_b = B()
 }

 class B{
   var object_a = A()
 }

Now consider your case : // CustomViewClass

- (void)showOnView: (UIView*)view {
    [view addSubview: self.customView];
}

Your" view" object is local variable .CustomViewClass doest not reference to superview "view".

Now when customview is added to superview:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.customViewClass showOnView: self.view];
}

When showOnView function of CustomViewClass called the superview simply adds subview CustomViewClass view.

For finding memory leaks always add deinit function in views and viewController class so that you can sure about class is deallocated or not.

deinit {
    print("deinit called " + "Class name")
}
like image 33
Dhruv Narayan Singh Avatar answered Nov 15 '22 05:11

Dhruv Narayan Singh