Root controllers and View Controllers

Discussion in 'iOS Programming' started by tjh21cen, Jan 7, 2009.

  1. tjh21cen macrumors newbie

    Jan 6, 2009
    I had a question about the View Controller hierarchy. I want to create a button within a view controller's view, not the root controller, that will switch in the next view. I tried to do this, but the view controller with the button doesn't know about the other view controllers and views, only the root view does.
    So i tried writing a method in the root controller that switches the views, but IB has no way of connecting the root view's method to a child view controller's view. In this case should I do something like [super switchViews]; within an IB method in the view controller with the button so it has access to the root controller's method? Or should I write the button for the controller view's view in code in the root controller bypassing IB altogether? Thanks
  2. drivefast macrumors regular

    Mar 13, 2008
    there are a few ways to do this, depends on which one wuld work best for you. let's consider you have the root view, the view with the button (let's call it view1) and the view that you want to show, view2.
    ( A ) you can instantiate a view2 object in the view1 code, and make it display;
    ( B ) you can pass a pointer to the root view to the view1 code, so that you can call the root view's function that would display view2;
    ( C ) from view1 you can send a notification to the root view, asking it to display view2.

    note that you may have a wrong perception about "super". "super" makes more sense in a hierarchy of classes, not in a hierarchy of objects.
  3. tjh21cen thread starter macrumors newbie

    Jan 6, 2009
    Option three seems like it might work the best, but how, more specifically, do I send a notification to the root view? Would that be a method? or some other device?
  4. drivefast macrumors regular

    Mar 13, 2008
    you subscribe to a notification with something like
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someHandlerFunction:) name:@"somemessagename" object:nil];
    and implement the handler function as
    - (void)someHandlerFunction:(NSNotification *)notification {}
    you trigger the execution of the handler function from pretty much anywhere by calling
    [[NSNotificationCenter defaultCenter] postNotificationName:@"somemessagename" object:someObject];
    a pointer to someObject will be passed to the handler function in the notification parameter (you can typecast it to whatever you need).

    apologies to everybody for my c++-ish accent.

Share This Page