Search code examples
uiviewcontrolleruisplitviewcontrollermaster-detailmethod-calldetailview

objective c: call method in masterViewController from detailViewController


I am using x-codes Master-detail template. I have a button in the detailView that has its action also in the detailViewController. Within this action method i need to call a method that is in the masterViewController. How can I do this ?


Solution

  • you need to get the reference of the masterViewController. use the delegate pattern.

    Init your detailViewController with this type of function :

    -(id)initWithDelegate:(id)deleg;
    

    with protocol :

     -(id)initWithDelegate:(id<myProtocol>)deleg;
    

    and had in your .h of detailViewController

    id delegate;
    

    with protocol :

    id<myProtocol> delegate;
    

    then in the .m of detail :

    -(id)initWithDelegate:(id)deleg
    {
        self = [super init];
        if(self)
        {
           delegate = deleg
        }
        return self;
    }
    

    then in your function

       -(IBAction)actionOfmyButton
        {
            if(delegate != nil && [delegate respondToSelector:@selector(functionFoo:)])
            {
               [delegate functionFoo:myArgumentsIfnecessary];
            }
        }
    

    Good luck ^^ !