简体   繁体   中英

iOS: Custom viewcontrollers as ivars

If I use a UICollectionView subclass within another UIViewController like so...

BrowseCVC *cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"BrowseItemVC"];
[self.containerScrollView addSubview:cvc.view];

... and either scroll the collection view or tap a cell, it will crash with EXC_BAD_ACCESS.

However if I declare it as a @property (strong, nonatomic) BrowseCVC *cvc; ) and use it like this...

self.cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"BrowseItemVC"];
[self.containerScrollView addSubview:self.cvc.view];

... everything works.

BorwseCVC is an unremarkable UICollectionViewController subclass with a very simple structure.

My question is: Why?

ARC takes care of memory management, but in these lines

BrowseCVC *cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"BrowseItemVC"];
[self.containerScrollView addSubview:cvc.view];

there's nothing to suggest to it that it should retain cvc. You only retain its view. cvc gets dealloced and you get exc_bad_access

As others have mentioned, BrowseCVC gets deallocated by ARC. You can work around this by either creating an iVar or property for it, or by adding it as a childViewController to your viewController:

BrowseCVC *cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"BrowseItemVC"];
[self addChildViewController:cvc];
[self.containerScrollView addSubview:cvc.view];

This should actually be the cleanest solution.

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