iOS app error - Can't add self as subview

Arnol picture Arnol · Oct 24, 2013 · Viewed 49.6k times · Source

I received this crash report, but I don't know how to debug it.

Fatal Exception NSInvalidArgumentException
Can't add self as subview
0 ...    CoreFoundation  __exceptionPreprocess + 130
1    libobjc.A.dylib     objc_exception_throw + 38
2    CoreFoundation  -[NSException initWithCoder:]
3    UIKit   -[UIView(Internal) _addSubview:positioned:relativeTo:] + 110
4    UIKit   -[UIView(Hierarchy) addSubview:] + 30
5    UIKit   __53-[_UINavigationParallaxTransition animateTransition:]_block_invoke + 1196
6    UIKit   +[UIView(Animation) performWithoutAnimation:] + 72
7    UIKit   -[_UINavigationParallaxTransition animateTransition:] + 732
8    UIKit   -[UINavigationController _startCustomTransition:] + 2616
9    UIKit   -[UINavigationController _startDeferredTransitionIfNeeded:] + 418
10   UIKit   -[UINavigationController __viewWillLayoutSubviews] + 44
11   UIKit   -[UILayoutContainerView layoutSubviews] + 184
12   UIKit   -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 346
13   QuartzCore  -[CALayer layoutSublayers] + 142
14   QuartzCore  CA::Layer::layout_if_needed(CA::Transaction*) + 350
15   QuartzCore  CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 16
16   QuartzCore  CA::Context::commit_transaction(CA::Transaction*) + 228
17   QuartzCore  CA::Transaction::commit() + 314
18   QuartzCore  CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 56

The iOS version is 7.0.3. Anyone experience this weird crash?

UPDATE:

I don't know where in my code caused this crash, so I can not post the code here, sorry.

Second UPDATE

See the answer below.

Answer

RobP picture RobP · Jan 20, 2014

I am speculating based on something similar that I debugged recently... if you push (or pop) a view controller with Animated:YES it doesn't complete right away, and bad things happen if you do another push or pop before the animation completes. You can easily test whether this is indeed the case by temporarily changing your Push and Pop operations to Animated:NO (so that they complete synchronously) and seeing if that eliminates the crash. If this is indeed your problem and you wish to turn animation back ON, then the correct strategy is to implement the UINavigationControllerDelegate protocol. This includes the following method, which is called after the animation is complete:

navigationController:didShowViewController:animated:

Basically you want to move some code as needed into this method to ensure that no other actions that could cause a change to the NavigationController stack will occur until the animation is finished and the stack is ready for more changes.