Callbacks and Protocols
At some point in designing an application, you may want to implement callbacks through protocols. To do this you just need to declare a protocol, have a delegate instance variable, and a method that calls your callback. The first part is simple, declare the protocol in the header:
@protocol MyClassDelegate <NSObject> -(void) myClassUpdate:(int)myVar; @end
This turns MyClassDelegate into a protocol, and declares that all classes using this protocol have to have the function myClassUpdate the way it is defined in the class. Now in your class interface, you have to declare your delegate variable, like so:
id <MyClassDelegate> delegate;
It's also very important that you make this delegate public, so other classes can add themselves to it. Now it's just a matter of calling the functions in the delegate variable, which we can do like so:
-(void) timerFired { if(delegate != nil && [delegate respondsToSelector:@selector(myClassUpdate:)]) [delegate myClassUpdate:3]; }
This calls myClassUpdate in our delegate, and finally to set our delegate variable:
MyClass* myClass = [[MyClass alloc] init]; myClass.delegate = self;
This will change the delegate variable so that it will call myClassUpdate when it needs to.