I know how delegates work, and I know how I can use them.
But how do I create them?
The approved answer is great, but if you're looking for a 1 minute answer try this:
MyClass.h file should look like this (add delegate lines with comments!)
#import
@class MyClass; //define class, so protocol can see MyClass
@protocol MyClassDelegate //define delegate protocol
- (void) myClassDelegateMethod: (MyClass *) sender; //define delegate method to be implemented within another class
@end //end protocol
@interface MyClass : NSObject {
}
@property (nonatomic, weak) id delegate; //define MyClassDelegate as delegate
@end
MyClass.m file should look like this
#import "MyClass.h"
@implementation MyClass
@synthesize delegate; //synthesise MyClassDelegate delegate
- (void) myMethodToDoStuff {
[self.delegate myClassDelegateMethod:self]; //this will call the method implemented in your other class
}
@end
To use your delegate in another class (UIViewController called MyVC in this case) MyVC.h:
#import "MyClass.h"
@interface MyVC:UIViewController { //make it a delegate for MyClassDelegate
}
MyVC.m:
myClass.delegate = self; //set its delegate to self somewhere
Implement delegate method
- (void) myClassDelegateMethod: (MyClass *) sender {
NSLog(@"Delegates are great!");
}