iOS app error - Can't add self as subview

IosIphoneObjective C

Ios Problem Overview


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.

Ios Solutions


Solution 1 - Ios

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.

Solution 2 - Ios

We started getting this issue as well, and chances were highly likely that ours were caused by the same problem.

In our case, we had to pull data from the back end in some cases, which meant a user might tap something and then there'd be a slight delay before the nav push occurred. If a user was rapidly tapping around, they might end up with two nav pushes from the same view controller, which triggered this very exception.

Our solution is a category on the UINavigationController which prevents pushes/pops unless the top vc is the same one from a given point in time.

.h file:

@interface UINavigationController (SafePushing)

- (id)navigationLock; ///< Obtain "lock" for pushing onto the navigation controller

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated navigationLock:(id)navigationLock; ///< Uses a horizontal slide transition. Has no effect if the view controller is already in the stack. Has no effect if navigationLock is not the current lock.
- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated navigationLock:(id)navigationLock; ///< Pops view controllers until the one specified is on top. Returns the popped controllers. Has no effect if navigationLock is not the current lock.
- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated navigationLock:(id)navigationLock; ///< Pops until there's only a single view controller left on the stack. Returns the popped controllers. Has no effect if navigationLock is not the current lock.

@end

.m file:

@implementation UINavigationController (SafePushing)

- (id)navigationLock
{
    return self.topViewController;
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated navigationLock:(id)navigationLock
{
    if (!navigationLock || self.topViewController == navigationLock) 
        [self pushViewController:viewController animated:animated];
}

- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated navigationLock:(id)navigationLock
{
    if (!navigationLock || self.topViewController == navigationLock)
        return [self popToRootViewControllerAnimated:animated];
    return @[];
}

- (NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated navigationLock:(id)navigationLock
{
    if (!navigationLock || self.topViewController == navigationLock)
        return [self popToViewController:viewController animated:animated];
    return @[];
}

@end

So far this seems to have resolved the problem for us. Example:

id lock = _dataViewController.navigationController.navigationLock;
[[MyApi sharedClient] getUserProfile:_user.id success:^(MyUser *user) {
    ProfileViewController *pvc = [[ProfileViewController alloc] initWithUser:user];
    [_dataViewController.navigationController pushViewController:pvc animated:YES navigationLock:lock];
}];

Basically, the rule is: before any non user related delays grab a lock from the relevant nav controller, and include it in the call to push/pop.

The word "lock" may be slightly poor wording as it may insinuate there's some form of lock happening that needs unlocking, but since there's no "unlock" method anywhere, it's probably okay.

(As a sidenote, "non user related delays" are any delays that the code is causing, i.e. anything asynchronous. Users tapping on a nav controller which is animatedly pushed doesn't count and there's no need to do the navigationLock: version for those cases.)

Solution 3 - Ios

This code resolves the issue: https://gist.github.com/nonamelive/9334458

It uses a private API, but I can confirm that it's App Store safe. (One of my apps using this code got approved by the App Store.)

@interface UINavigationController (DMNavigationController)
 
- (void)didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
 
@end
 
@interface DMNavigationController ()
 
@property (nonatomic, assign) BOOL shouldIgnorePushingViewControllers;
 
@end
 
@implementation DMNavigationViewController
 
#pragma mark - Push
 
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (!self.shouldIgnorePushingViewControllers)
    {
        [super pushViewController:viewController animated:animated];
    }
    
    self.shouldIgnorePushingViewControllers = YES;
}
 
#pragma mark - Private API
 
// This is confirmed to be App Store safe.
// If you feel uncomfortable to use Private API, you could also use the delegate method navigationController:didShowViewController:animated:.
- (void)didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [super didShowViewController:viewController animated:animated];
    self.shouldIgnorePushingViewControllers = NO;
}

Solution 4 - Ios

I will describe more details about this crash in my app and mark this as answered.

My app has a UINavigationController with the root controller is a UITableViewController that contains a list of note objects. The note object has a content property in html. Select a note will go to the detail controller.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	//get note object
	DetailViewController *controller = [[DetailViewController alloc] initWithNote:note];
	[self.navigationController pushViewController:controller animated:YES];
}
Detail controller

This controller has a UIWebView, display the note content passed from the root controller.

- (void)viewDidLoad
{
	...
	[_webView loadHTMLString:note.content baseURL:nil];
	...
}

This controller is the delegate of the webview control. If the note contains links, tap a link will go to the in-app web browser.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	WebBrowserViewController *browserController = [[WebBrowserViewController alloc] init];
	browserController.startupURL = request.URL;
	[self.navigationController pushViewController:webViewController animated:YES];
	return NO;
}

I received the above crash report everyday. I don't know where in my code caused this crash. After some investigates with the help of a user, I was finally able to fix this crash. This html content will cause the crash:

...
<iframe src="http://google.com"></iframe>
...

In the viewDidLoad method of the detail controller, I loaded this html to the webview control, right after that, the above delegate method was called immediately with request.URL is the iframe's source (google.com). This delegate method calls pushViewController method while in viewDidLoad => crash!

I fixed this crash by checking the navigationType:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	if (navigationType != UIWebViewNavigationTypeOther)
	{
		//go to web browser controller
	}
}

Hope this helps

Solution 5 - Ios

I had the same issue, what simply worked for me was changing Animated:Yes to Animated:No.

It looks like the issue was due to the animation not completing in time.

Hope this helps someone.

Solution 6 - Ios

To reproduce this bug, try pushing two view controllers at the same time. Or pushing and poping at the same. Example:

enter image description here I have created a category which intercepts these calls and makes them safe by making sure that no other pushes are happening while one is in progress. Just copy the code into your project and due to method swizzling you'll be good to go.

#import "UINavigationController+Consistent.h"
#import <objc/runtime.h>
/// This char is used to add storage for the isPushingViewController property.
static char const * const ObjectTagKey = "ObjectTag";

@interface UINavigationController ()
@property (readwrite,getter = isViewTransitionInProgress) BOOL viewTransitionInProgress;

@end

@implementation UINavigationController (Consistent)

- (void)setViewTransitionInProgress:(BOOL)property {
    NSNumber *number = [NSNumber numberWithBool:property];
    objc_setAssociatedObject(self, ObjectTagKey, number , OBJC_ASSOCIATION_RETAIN);
}


- (BOOL)isViewTransitionInProgress {
    NSNumber *number = objc_getAssociatedObject(self, ObjectTagKey);
    
    return [number boolValue];
}


#pragma mark - Intercept Pop, Push, PopToRootVC
/// @name Intercept Pop, Push, PopToRootVC

- (NSArray *)safePopToRootViewControllerAnimated:(BOOL)animated {
    if (self.viewTransitionInProgress) return nil;
    if (animated) {
        self.viewTransitionInProgress = YES;
    }
    //-- This is not a recursion, due to method swizzling the call below calls the original  method.
    return [self safePopToRootViewControllerAnimated:animated];

}


- (NSArray *)safePopToViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.viewTransitionInProgress) return nil;
    if (animated) {
        self.viewTransitionInProgress = YES;
    }
    //-- This is not a recursion, due to method swizzling the call below calls the original  method.
    return [self safePopToViewController:viewController animated:animated];
}


- (UIViewController *)safePopViewControllerAnimated:(BOOL)animated {
    if (self.viewTransitionInProgress) return nil;
    if (animated) {
        self.viewTransitionInProgress = YES;
    }
    //-- This is not a recursion, due to method swizzling the call below calls the original  method.
    return [self safePopViewControllerAnimated:animated];
}



- (void)safePushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    self.delegate = self;
    //-- If we are already pushing a view controller, we dont push another one.
    if (self.isViewTransitionInProgress == NO) {
        //-- This is not a recursion, due to method swizzling the call below calls the original  method.
        [self safePushViewController:viewController animated:animated];
        if (animated) {
            self.viewTransitionInProgress = YES;
        }
    }
}


// This is confirmed to be App Store safe.
// If you feel uncomfortable to use Private API, you could also use the delegate method navigationController:didShowViewController:animated:.
- (void)safeDidShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    //-- This is not a recursion. Due to method swizzling this is calling the original method.
    [self safeDidShowViewController:viewController animated:animated];
    self.viewTransitionInProgress = NO;
}


// If the user doesnt complete the swipe-to-go-back gesture, we need to intercept it and set the flag to NO again.
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    id<UIViewControllerTransitionCoordinator> tc = navigationController.topViewController.transitionCoordinator;
    [tc notifyWhenInteractionEndsUsingBlock:^(id<UIViewControllerTransitionCoordinatorContext> context) {        self.viewTransitionInProgress = NO;        //--Reenable swipe back gesture.        self.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)viewController;        [self.interactivePopGestureRecognizer setEnabled:YES];
    }];
    //-- Method swizzling wont work in the case of a delegate so:
    //-- forward this method to the original delegate if there is one different than ourselves.
    if (navigationController.delegate != self) {
        [navigationController.delegate navigationController:navigationController                                     willShowViewController:viewController                                                   animated:animated];
    }
}


+ (void)load {
    //-- Exchange the original implementation with our custom one.
    method_exchangeImplementations(class_getInstanceMethod(self, @selector(pushViewController:animated:)), class_getInstanceMethod(self, @selector(safePushViewController:animated:)));
    method_exchangeImplementations(class_getInstanceMethod(self, @selector(didShowViewController:animated:)), class_getInstanceMethod(self, @selector(safeDidShowViewController:animated:)));
    method_exchangeImplementations(class_getInstanceMethod(self, @selector(popViewControllerAnimated:)), class_getInstanceMethod(self, @selector(safePopViewControllerAnimated:)));
    method_exchangeImplementations(class_getInstanceMethod(self, @selector(popToRootViewControllerAnimated:)), class_getInstanceMethod(self, @selector(safePopToRootViewControllerAnimated:)));
    method_exchangeImplementations(class_getInstanceMethod(self, @selector(popToViewController:animated:)), class_getInstanceMethod(self, @selector(safePopToViewController:animated:)));
}

@end

Solution 7 - Ios

Just experienced this issue as well. Let me show you my code :

override func viewDidLoad() { 
  super.viewDidLoad()
  
  //First, I create a UIView
  let firstFrame = CGRect(x: 50, y: 70, height: 200, width: 200)
  let firstView = UIView(frame: firstFrame)
  firstView.addBackgroundColor = UIColor.yellow
  view.addSubview(firstView) 
  
  //Now, I want to add a subview inside firstView
  let secondFrame = CGRect(x: 20, y:50, height: 15, width: 35)
  let secondView = UIView(frame: secondFrame)
  secondView.addBackgroundColor = UIColor.green
  firstView.addSubView(firstView)
 }

The error comes up due to this line :

firstView.addSubView(firstView)

You can't add self to subview. I changed the line of code to :

firstView.addSubView(secondView)

The error went away and I was able to see both of the views. Just thought this would help anyone who wanted to see an example.

Solution 8 - Ios

Sometimes you mistakenly tried to add a view to its own view.

halfView.addSubview(halfView)

change this to your sub view.

halfView.addSubview(favView)

Solution 9 - Ios

Search your code for "addSubview".

In one of the places you called this method you tried to add a view to its own sub views array using this method.

For example:

[self.view addSubview:self.view];

Or:

[self.myLabel addSubview:self.myLabel];

Solution 10 - Ios

I think that pushing/popping view controllers with animation at any point should be perfectly fine and the SDK should graciously handle the queue of calls for us.

Hence it doesn't and all the solutions try to ignore subsequent pushes, which could be considered a bug since the final navigation stack is not what the code intended.

I implemented a push calls queue instead:

// SafeNavigationController.h

@interface SafeNavigationController : UINavigationController
@end

 

// SafeNavigationController.m

#define timeToWaitBetweenAnimations 0.5

@interface SafeNavigationController ()

@property (nonatomic, strong) NSMutableArray * controllersQueue;
@property (nonatomic)         BOOL animateLastQueuedController;
@property (nonatomic)         BOOL pushScheduled;
@property (nonatomic, strong) NSDate * lastAnimatedPushDate;

@end

@implementation SafeNavigationController

- (void)awakeFromNib
{
    [super awakeFromNib];
    
    self.controllersQueue = [NSMutableArray array];
}

- (void)pushViewController:(UIViewController *)viewController
                  animated:(BOOL)animated
{
    [self.controllersQueue addObject:viewController];
    self.animateLastQueuedController = animated;
    
    if (self.pushScheduled)
        return;
    
    // Wait for push animation to finish
    NSTimeInterval timeToWait = self.lastAnimatedPushDate ? timeToWaitBetweenAnimations + [self.lastAnimatedPushDate timeIntervalSinceNow] : 0.0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((timeToWait > 0.0 ? timeToWait : 0.0) * NSEC_PER_SEC)),
                   dispatch_get_main_queue(), ^
                   {
                       [self pushQueuedControllers];
                       
                       self.lastAnimatedPushDate = self.animateLastQueuedController ? [NSDate date] : nil;
                       self.pushScheduled = NO;
                   });
    self.pushScheduled = YES;
}

- (void)pushQueuedControllers
{
    for (NSInteger index = 0; index < (NSInteger)self.controllersQueue.count - 1; index++)
    {
        [super pushViewController:self.controllersQueue[index]
                         animated:NO];
    }
    [super pushViewController:self.controllersQueue.lastObject
                     animated:self.animateLastQueuedController];

    [self.controllersQueue removeAllObjects];
}

@end

It doesn't handle mixed queues of push and pops but it's a good starter to fix most of our crashes.

Gist: https://gist.github.com/rivera-ernesto/0bc628be1e24ff5704ae

Solution 11 - Ios

Sorry for being late for the party. I recently had this issue wherein my navigationbar goes into corrupted state because of pushing more than one view controller at the same time. This happens because the other view controller is pushed while the first view controller is still animating. Taking hint from the nonamelive answer I came up with my simple solution that works in my case. You just need to subclass UINavigationController and override the pushViewController method and check if previous view controller animation is finished as yet. You can listen to the animation completion by making your class a delegate of UINavigationControllerDelegate and setting the delegate to self.

I have uploaded a gist here to make things simple.

Just make sure you set this new class as the NavigationController in your storyboard.

Solution 12 - Ios

Based on @RobP great hint I made UINavigationController subclass in order to prevent such problems. It handles pushing and/or popping and you can safely execute:

[self.navigationController pushViewController:vc1 animated:YES];
[self.navigationController pushViewController:vc2 animated:YES];
[self.navigationController pushViewController:vc3 animated:YES];
[self.navigationController popViewControllerAnimated:YES];

If 'acceptConflictingCommands' flag it true(by default) user will see animated pushing of vc1, vc2, vc3 and then will see animated popping of vc3. If 'acceptConflictingCommands' is false, all push/pop requests will be discarded until vc1 is fully pushed - hence other 3 calls will be discarded.

Solution 13 - Ios

nonamelive's solution is awesome. But if you don't want to use the private api, you can just achieve the UINavigationControllerDelegate method.Or you can change the animated YES to NO. Here is a sample of code, you can inherit it. Hope it's helpful : )

https://github.com/antrix1989/ANNavigationController

Solution 14 - Ios

I had searched this problem a lot, it maybe pushing two or more VC at same time, which cause the pushing animation problem, you can refer to this :Can't Add Self as Subview 崩溃解决办法

just make sure the there is one VC on transition progress at same time,good luck.

Solution 15 - Ios

I also encountered this problem. When I did Firebase log analysis, I found that this problem only occurs when the app is cold started. So I wrote a demo that can reproduce this crash.

.

I also found that when the window's root viewcontroller is displayed, performing multiple pushes will not cause the same problem again. (You can comment testColdStartUp(rootNav) in AppDelegate.swift, and uncomment the testColdStartUp() comment in ViewController.swift)

ps: I analyzed the scene of this crash in my app. When the user clicks the push notification to cold start the app, the app is still on the Launch page and clicks another push to jump. At this time, the app may appear the Crash. My current The solution is to cache the push or Universal link cold start to open the App jump page, wait for the rootviewcontroller to display, and then delay execution.

Solution 16 - Ios

try your navigation using delay method, for completing the last navigation animation,

[self performSelector:<#(SEL)#> withObject:<#(id)#> afterDelay:<#(NSTimeInterval)#>]

Solution 17 - Ios

A view can not be added as a subview in it self.

The views maintains a parent-child hierarchy so if you add a view as a subview in itself it will through exception.

if a class is UIViewController then to get its view you use self.view.

if a class is UIView Class then to get its view you use self.

Solution 18 - Ios

you cannot add self as subview if it is going to be a UiViewController Class. you can add self as subview if it is going to be a UiView Class.

Solution 19 - Ios

If you like to add a Subview to a View you can do it like this;

UIView *mainview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; //Creats the mainview
    UIView *subview = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; //Creates the subview, you can use any kind of Views (UIImageView, UIWebView, UIView…)
    
    [mainview addSubview:subview]; //Adds subview to mainview

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArnolView Question on Stackoverflow
Solution 1 - IosRobPView Answer on Stackoverflow
Solution 2 - IosKalleView Answer on Stackoverflow
Solution 3 - IosnonameliveView Answer on Stackoverflow
Solution 4 - IosArnolView Answer on Stackoverflow
Solution 5 - IosLion789View Answer on Stackoverflow
Solution 6 - IosdanView Answer on Stackoverflow
Solution 7 - Ioshalapgos1View Answer on Stackoverflow
Solution 8 - IosVinoth VinoView Answer on Stackoverflow
Solution 9 - IosMichal ShatzView Answer on Stackoverflow
Solution 10 - IosRiveraView Answer on Stackoverflow
Solution 11 - Iosnikhil.thakkarView Answer on Stackoverflow
Solution 12 - Ioshris.toView Answer on Stackoverflow
Solution 13 - IosNSKevinView Answer on Stackoverflow
Solution 14 - IosMichaelMaoView Answer on Stackoverflow
Solution 15 - IosJader YangView Answer on Stackoverflow
Solution 16 - IosNaeem ParachaView Answer on Stackoverflow
Solution 17 - IosMradul KumarView Answer on Stackoverflow
Solution 18 - Iosuser1533983View Answer on Stackoverflow
Solution 19 - IosDavid GölzhäuserView Answer on Stackoverflow