0

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 ?

pnizzle
  • 6,243
  • 4
  • 52
  • 81

1 Answers1

1

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 ^^ !

xeonarno
  • 426
  • 6
  • 17
  • I now have the initWithDelegate:() method listed in my detailViewcontroller.h and defined in detailViewcontroller.m. I have also added the code for my action. I am however not sure what I'm supposed to do with the rest of the code u have provided there.. some help please.. – pnizzle May 23 '12 at 06:07
  • 1
    if(delegate != nil && [delegate respondToSelector:@selector(functionFoo:)]) { [delegate functionFoo:myArgumentsIfnecessary]; } – xeonarno May 24 '12 at 13:56
  • 1
    inside your MasterViewController you need to add the function -(void)functionFoo:(thetypeofyourVariable)yourVariable) and automaticly the functionFoo will be call by your detailViewController in the MasterViewController. It's called the delegate Pattern. hope it's helping you. – xeonarno May 24 '12 at 13:59
  • Could you check the answer please ! – xeonarno Jun 27 '12 at 00:15
  • hey, I didn't get the chance to check that code out, the project I was working on was temporarily put aside and I have no access to it. Never the less, i will create a simple app that mimics the situation and then test your suggestion. Thank you for that – pnizzle Jun 27 '12 at 01:39
  • played around with the code, and finally got it working. I think this master-detail template in the future should allow us to do something like [self.masterViewController myMethodInMaster] from the detailViewController by default. Thanks for the help, learnt something really useful – pnizzle Jun 28 '12 at 01:29
  • No ! try to avoid that. Because you create dependance between both objects. Imagine that one day you will change the masterViewController class to another. It will be complicated. Good luck – xeonarno Nov 22 '12 at 00:53
  • i very much understand what you mean. I was quite new to a number of things in object oriented programming when I asked the question, and I'm still learning – pnizzle Nov 25 '12 at 03:10