I know how delegates work, and I know how I can use them.
But how do I create them?
lets say you have a class that you developed and want to declare a delegate property to be able to notify it when some event happens :
@class myClass;
@protocol myClassDelegate
-(void)myClass:(MyClass*)myObject requiredEventHandlerWithParameter:(ParamType*)param;
@optional
-(void)myClass:(MyClass*)myObject optionalEventHandlerWithParameter:(ParamType*)param;
@end
@interface MyClass : NSObject
@property(nonatomic,weak)id< MyClassDelegate> delegate;
@end
so you declare a protocol in MyClass
header file (or a separate header file) , and declare the required/optional event handlers that your delegate must/should implement , then declare a property in MyClass
of type (id< MyClassDelegate>
) which means any objective c class that conforms to the protocol MyClassDelegate
, you'll notice that the delegate property is declared as weak , this is very important to prevent retain cycle (most often the delegate retains the MyClass
instance so if you declared the delegate as retain, both of them will retain each other and neither of them will ever be released).
you will notice also that the protocol methods passes the MyClass
instance to the delegate as parameter , this is best practice in case the delegate want to call some methods on MyClass
instance and also helps when the delegate declares itself as MyClassDelegate
to multiple MyClass
instances , like when you have multiple UITableView's
instances in your ViewController
and declares itself as a UITableViewDelegate
to all of them.
and inside your MyClass
you notify the delegate with declared events as follows :
if([_delegate respondsToSelector:@selector(myClass: requiredEventHandlerWithParameter:)])
{
[_delegate myClass:self requiredEventHandlerWithParameter:(ParamType*)param];
}
you first check if your delegate responds to the protocol method that you are about to call in case the delegate doesn't implement it and the app will crash then (even if the protocol method is required).