I’m currently learning Obj-C and more specifically – protocols. I will need to make up a scenario here for my question to make sense.
First example (with a delegate).
-
I’m a UIView subclass which requests information from it’s controller to be displayed (or rather how the information should be displayed). I declare a protocol and make a delegate reference object (or whatever it’s called):
@property (nonatomic, weak) id <protocolName> dataSource; -
My controller conforms to this protocol and implements the required method.
- View sends messages to the Controller, and the Controller answers and everything is fine.
This as far as I know is delegation through protocols and I believe I understand it.
But let’s consider another scenario.
- I’m a class which is the brain for a simple level-based game. I say when to show the menu or when to start playing a game level. But I need to know when a level is completed.
Which means this class needs to be ready to receive messages from anyone that implements the protocol, for example from another class which is responsible for the current level. Now this is what I don’t understand. How the protocol should look like and where/how to implement it?
Let me know if my question still doesn’t make sense. Thanks!
Delegate is a one-to-on relationship method for sending message between entities.
If you want to receive the same message from different class, you can use
NSNotificationthat is a one-to-many relationship.Look at the
NSNotificationCenterclass, especiallypostNotificationmethod (for sending messages) andaddObservermethod (used when received a notification)EDIT :
Here’s an example code for delegation.
Let’s take your game level-based example. You have a
LevelManagerclass andFirstLevelclass. If you want theLevelManagerto be notice when theFirstLevelended, you have to declare a protocol in yourFirstLevelclassThen somewhere in your FirstLevel.m, call your protocol method when the level ended
The next step is to implement your protocol to your LevelManager :
And then, set your
firstLevel.delegateand implement your protocol method