Zoltán Matók
Zoltán Matók

Reputation: 4045

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?

Upvotes: 0

Views: 69

Answers (2)

fzwo
fzwo

Reputation: 9902

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.

Upvotes: 2

johnyu
johnyu

Reputation: 2151

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

Upvotes: 2

Related Questions