只是为了确保我们在同一页面上:)
如果ClassA
有委托ClassADelegate
。这意味着当某些“事件”发生在 中时ClassA
,ClassA
将希望通过其委托通知其他类“事件”发生 - ClassB
。ClassA
将通过其委托 - 执行此操作ClassADelegate
。
为此,ClassB
必须ClassA
告知它将充当ClassA
' 代表。ClassB
必须ClassA
通过实现协议中列出的所有未标记为@optional 的方法来“符合”协议。
在代码中,您可以这样做:
// 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"];
}
现在我们需要进行连接,ClassB
以便通知它发生了一些事情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
现在在ClassB
的实现文件中的某个地方,我们有以下内容。
// 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
我希望这有帮助 :)