我知道委托(delegate)是如何工作的,并且我知道如何使用它们。
但是我该如何创建它们呢?
最佳答案
Objective-C 委托(delegate)是一个对象,它已分配给另一个对象的 delegate
属性。要创建一个,您定义一个实现您感兴趣的委托(delegate)方法的类,并将该类标记为实现委托(delegate)协议(protocol)。
例如,假设您有一个 UIWebView
。如果你想实现它的委托(delegate)webViewDidStartLoad:
方法,你可以像这样创建一个类:
@interface MyClass<UIWebViewDelegate>
// ...
@end
@implementation MyClass
- (void)webViewDidStartLoad:(UIWebView *)webView {
// ...
}
@end
然后您可以创建 MyClass 的实例并将其分配为 Web View 的委托(delegate):
MyClass *instanceOfMyClass = [[MyClass alloc] init];
myWebView.delegate = instanceOfMyClass;
在 UIWebView
方面,它可能有类似的代码来查看代理是否使用 respondsToSelector:
响应 webViewDidStartLoad:
消息并在适当的时候发送。
if([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
[self.delegate webViewDidStartLoad:self];
}
delegate 属性本身通常被声明为 weak
(在 ARC 中)或 assign
(pre-ARC)以避免保留循环,因为对象的委托(delegate)通常持有对该对象的强引用。 (例如, View Controller 通常是它所包含的 View 的委托(delegate)。)
要定义自己的委托(delegate),您必须在某处声明它们的方法,如 Apple Docs on protocols 中所述。 .你通常声明一个正式的协议(protocol)。从 UIWebView.h 解释的声明如下所示:
@protocol UIWebViewDelegate <NSObject>
@optional
- (void)webViewDidStartLoad:(UIWebView *)webView;
// ... other methods here
@end
这类似于接口(interface)或抽象基类,因为它为您的委托(delegate)创建了一个特殊类型,在本例中为 UIWebViewDelegate
。委托(delegate)实现者必须采用此协议(protocol):
@interface MyClass <UIWebViewDelegate>
// ...
@end
然后实现协议(protocol)中的方法。对于在协议(protocol)中声明为 @optional
的方法(与大多数委托(delegate)方法一样),您需要在调用特定方法之前检查 -respondsToSelector:
。
委托(delegate)方法通常以委托(delegate)类名称开头,并将委托(delegate)对象作为第一个参数。他们还经常使用 will-、should- 或 did- 形式。因此,例如,webViewDidStartLoad:
(第一个参数是 web View )而不是 loadStarted
(不带参数)。
您可以在设置代理时缓存该信息,而不是每次我们要向选择器发送消息时检查代理是否响应选择器。一种非常简洁的方法是使用位域,如下所示:
@protocol SomethingDelegate <NSObject>
@optional
- (void)something:(id)something didFinishLoadingItem:(id)item;
- (void)something:(id)something didFailWithError:(NSError *)error;
@end
@interface Something : NSObject
@property (nonatomic, weak) id <SomethingDelegate> delegate;
@end
@implementation Something {
struct {
unsigned int didFinishLoadingItem:1;
unsigned int didFailWithError:1;
} delegateRespondsTo;
}
@synthesize delegate;
- (void)setDelegate:(id <SomethingDelegate>)aDelegate {
if (delegate != aDelegate) {
delegate = aDelegate;
delegateRespondsTo.didFinishLoadingItem = [delegate respondsToSelector:@selector(something:didFinishLoadingItem:)];
delegateRespondsTo.didFailWithError = [delegate respondsToSelector:@selector(something:didFailWithError:)];
}
}
@end
然后,在正文中,我们可以通过访问我们的 delegateRespondsTo
结构而不是一遍又一遍地发送 -respondsToSelector:
来检查我们的委托(delegate)是否处理了消息。
在协议(protocol)存在之前,通常使用 category在 NSObject
上声明委托(delegate)可以实现的方法。例如,CALayer
仍然这样做:
@interface NSObject(CALayerDelegate)
- (void)displayLayer:(CALayer *)layer;
// ... other methods here
@end
这告诉编译器任何对象都可能实现 displayLayer:
.
然后,您将使用与上述相同的 -respondsToSelector:
方法来调用此方法。委托(delegate)实现此方法并分配 delegate
属性,仅此而已(没有声明您符合协议(protocol))。这种方法在 Apple 的库中很常见,但是新代码应该使用上面更现代的协议(protocol)方法,因为这种方法会污染 NSObject
(这使得自动完成不太有用)并且编译器很难警告你拼写错误和类似错误。
https://stackoverflow.com/questions/626898/