iPhone - difference between topViewController and other forms

10,517

Solution 1

topViewController of a navigation controller represents the view controller at the top of the stack. Index 0 is the bottom. topViewController is the object at index 0 only when one view controller is on the stack. If you have more than one, it is not the same. I am guessing that it is the case as it's crashing because the topViewController doesn't know how to respond to messages intended for a RootViewController instance.

Solution 2

You can check what type of class is being returned with

    NSString *className = NSStringFromClass([[self.navigationController topViewController] class]); 
    NSLog(@"class name is: %@", className);

If you want to check before accessing, I'd use:

if ([[self.navigationController topViewController] isKindOfClass:[RootViewController class]])
Share:
10,517
Duck
Author by

Duck

Updated on June 09, 2022

Comments

  • Duck
    Duck almost 2 years

    I am on a delegate of a NavigationControl based app.

    when I try to access the rootViewController using

    RootViewController *rootViewController = (RootViewController *)[navigationController topViewController];
    

    to run a method, it crashes, saying the method is "unknown" on the rootViewController.

    When I access the rootViewController using this

    RootViewController *rootViewController = (RootViewController *)[navigationController.viewControllers objectAtIndex:0];
    

    it works.

    Which object is the first line accessing?

    thanks

  • Duck
    Duck almost 13 years
    The app has several viewControllers but they are just created lazily. In theory, after the delegate initializes it will initialize the RootViewController, and there's no other viewController initialized at this time. This is why I don't understand this.
  • Duck
    Duck almost 13 years
    the first one returns Main and the second one returns RootViewController that is what I want. The big question is: what is this "Main" view controller? I have not created that, at least not that I know. I have started the project using the NavigationController template from Xcode.
  • Noor
    Noor over 10 years
    you solved my one of the biggest problem ... thannnkkkssssssss