1

I've recently started developing for the iPhone and so far I'm doing pretty good but there's this basic pattern I really don't seem to get.

Say, I have a TabBar with two views and a custom delegate protocol, thus my structure is the following:

  • AppDelegate.h/.m
  • myDelegateProtocol.h
  • FirstViewController.h/.m
  • SecondViewController.h/.m
  • MainView.xib
  • FirstView.xib
  • SecondView.xib

Now I want to achieve the following: I placed a button in the FirstView.xib and I'd like the IBAction which it invokes (inside FirstViewController ofc.) to send a message to the SecondViewController ([self.delegate tellSecondViewContrToSayHi]) and invoke another method which simply prints a log into the console saying "hi I'm here."

So far I know what I need to do in theory:

  1. Specify the protocol.
  2. Implement the protocol in the SecondViewController.
  3. Create an id< myDelegateProtocol > delegate inside my FirstViewController,...AND last but not least:
  4. Set the self.delegate = secondViewControllerObject.

Now, nr.4 is where the problem's at. How on earth do I link the delegate to the other viewController? I mean I'm not the one instantiating the views as the tabBar kinda does that for me,... any advise? Or am I just way too tired to notice a really stupid thing I did somewhere?

Theoretically the same question also applies to the target:action: thing,... I mean, how do I define the target?

Thanks a lot, wasabi

pkluz
  • 4,871
  • 4
  • 26
  • 40
  • I'm curious if your design is sound. It kind of seems like you might be trying to use the delegate in a funny way. – Todd Hopkinson Apr 20 '11 at 21:05
  • You're correct! This has actually no real application in any of my apps, I'm just being curious and toying around in order to, well...figure things out and understand the mechanics :) – pkluz Apr 20 '11 at 21:20
  • 2
    Check this out, it has pretty good info: http://stackoverflow.com/questions/626898/how-do-i-create-delegates-in-objective-c – Todd Hopkinson Apr 20 '11 at 21:32

1 Answers1

2

You have the right idea, assuming that you want relatively tight coupling between these controllers via that delegate protocol.

Since neither controller knows about the other until that delegate property is set you need to have some object which has a reference to both of them wire up that relationship. In your case that's probably the application delegate which can create both controllers, set one as the delegate of the other, and pass both along to your tab bar controller.

What you might actually want is to have the app delegate give both controllers a reference to some shared model object. Your FirstViewController can update that model when you tap a button and your SecondViewController can observe changes to the model to update it's display (or just update its view when it appears based on the current model state). That way your controllers don't need to know anything about each other.

Jonah
  • 17,918
  • 1
  • 43
  • 70