简体   繁体   中英

Is adding a subview to a view a retain cycle?

I need to know if this is a retain cycle. I ran this in leaks instruments and I did not get any leaks.

class myClass: UICollectionViewCell {
   var aView = UIView()

   func test() {
       self.addSubView(aView)
   }
}

This code doesn't cause a retain cycle, but it doesn't work in practice either.

A view is required to be initialized with a (suitable) frame.

If you want to create retain cycles in Swift ( i hope just for study) you should always make present that a reference to an instance function means that you're referencing the instance as well. And when assigning to a variable, you're creating a strong reference. Make sure to wrap such references in a closure with a weak reference to the instance or make sure to manually set the variables to nil once you're done with them

No it will not increase retain cycle

This Example will help you to get better idea

@interface TTParent : NSObject
 @property (atomic) NSMutableArray *children;
@end

@implementation TTParent

@end

@interface TTChild : NSObject

 @property (atomic) TTParent *parent;

@end

@implementation TTChild

@end

In Some Other Class

  TTParent *parent = [[TTParent alloc] init];
  parent.children = [[NSMutableArray alloc] init];
  for (int i = 0; i < 10; i++) {
     TTChild *child = [[TTChild alloc] init];
     child.parent = parent;
     [parent.children addObject:child];

 }

It will Increase Retail Cycle because both Parent and child has strong reference of each other

to avoid this

@property (atomic,weak) TTParent *parent;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM