我想子类化 UITextView,并向代理发送一条新消息。所以,我想扩展委托(delegate)协议(protocol)。执行此操作的正确方法是什么?
我从这个开始:
界面:
#import <Foundation/Foundation.h>
@class MySubClass;
@protocol MySubClassDelegate <UITextViewDelegate>
- (void) MySubClassMessage: (MySubClass *) subclass;
@end
@interface MySubClass : UITextView {
}
@end
实现:
#import "MySubClass.h"
@implementation MySubClass
- (void) SomeMethod; {
if ([self.delegate respondsToSelector: @selector (MySubClassMessage:)]) {
[self.delegate MySubClassMessage: self];
}
}
@end
然而,我收到警告:'-MySubClassMessage:' not found in protocol(s)
。
我有一种工作方式,我创建自己的 ivar 来存储委托(delegate),然后还使用 [super setDelegate]
存储委托(delegate),但这似乎是错误的。也许不是。
我知道我可以传递 id 并通过,但我的目标是确保编译器检查提供给 MySubClass 的任何委托(delegate)是否符合 MySubClassDelegate 协议(protocol)。
为了进一步澄清:
@interface MySubClassTester : NSObject {
}
@implementation MySubClassTester
- (void) one {
MySubClass *subclass = [[MySubClass alloc] init];
subclass.delegate = self;
}
@end
将产生警告:class 'MySubClassTester' does not implement the 'UITextViewDelegate' protocol
我希望它产生关于不实现“MySubClassDelegate”协议(protocol)的警告。
最佳答案
UITextView
将其delegate
定义为
@property(nonatomic, assign) id<UITextViewDelegate> delegate
意味着它符合 UITextViewDelegate
,这是编译器检查的内容。如果你想使用新的协议(protocol),你需要重新定义delegate
来符合你的协议(protocol):
@interface MySubClass : UITextView {
}
@property(nonatomic, assign) id<MySubClassDelegate> delegate
@end
编译器不应再给出任何警告。
[fess更新]
...有了这个,编译器将警告需要实现访问器...[我实现了这个:]
-(void) setDelegate:(id<MySubClassDelegate>) delegate {
[super setDelegate: delegate];
}
- (id) delegate {
return [super delegate];
}
”
[我的更新]
我相信如果你只做一个 @dynamic
声明而不是重新实现该方法,它应该可以工作,因为实现已经存在:
@dynamic delegate;
关于iphone - 如何在 Objective-C 中为委托(delegate)扩展协议(protocol),然后将对象子类化以需要符合要求的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2859584/