Just to make sure that we are on the same page :)
If ClassA
has a delegate ClassADelegate
. What this means is that when some "event" occurs in ClassA
, ClassA
will want to notify some other class via its delegate that the "event" occurred - ClassB
. ClassA
will do this via its delegate - ClassADelegate
.
For this to happen, ClassB
will have to let ClassA
know that it will be acting as ClassA
's delegate. ClassB
will have to "conform" to ClassA
's protocol by implementing all of the methods listed in the protocol that not marked as @optional.
In code, you could do this:
// ClassA's delegate
@protocol ClassADelegate <NSObject>
- (void) didDoSomethingCool:(NSString *) name;
@end
// ClassA definition
@interface ClassA
// We'll use this property to call the delegate.
// id<XXX> means that which ever class is assigned to id MUST conform to XXX
@property (nonatomic, assign) id<ClassADelegate> classADelegate;
- (void) doSomething;
@end
// Class A implementation
@implementation ClassA
@synthesize classADelegate;
- (void) doSomething
{
// Do cool things here.
// Now call delegate, in this example, this will be ClassB
[classADelegate didDoSomethingCool:@"Hello from Class A"];
}
Now we need to wire-up ClassB
so that it can be notified that something happened in ClassA
:
// ClassB definition
@interface ClassB<ClassADelegate>
// ClassB<ClassADelegate> lets the compiler know that ClassB is required to have all the
// non-optional method that are listed in ClassADelegate. In short, we say that
// ClassB conforms to the ClassADelegate.
{
ClassA *_classA;
}
@end
Now somewhere in ClassB
's implementation file we have the following.
// ClassB implementation
@implementation ClassB
- (id) init
{
self = [super init];
if(self)
{
// Just quickly creating an instance of ClassA.
_classA = [ClassA new];
// This is were we tell ClassA that ClassB is its delegate.
_classA.classADelegate = self;
}
return self;
}
- (void) dealloc
{
[_classA release];
[super dealloc];
}
- (void) didDoSomethingCool:(NSString *) name
{
// This is the method that ClassA will be calling via the
// [classADelegate didDoSomethingCool:@"Hello from Class A"] method call.
}
@end
I hope this helps :)