我继承的一些代码有一个恼人的警告。它声明一个协议,然后使用它来指定
@protocol MyTextFieldDelegate;
@interface MyTextField: UITextField
@property (nonatomic, assign) id<MyTextFieldDelegate> delegate;
@end
@protocol MyTextFieldDelegate <UITextFieldDelegate>
@optional
- (void)myTextFieldSomethingHappened:(MyTextField *)textField;
@end
使用 myTextField
的委托类实现 MyTextFieldDelegate
并使用以下代码调用它:
if ([delegate respondsToSelector:@selector(myTextFieldSomethingHappened:)])
{
[delegate myTextFieldSomethingHappened:self];
}
这有效,但创建了(合法的)警告:警告:属性类型“id”与从“UITextField”继承的类型“id”不兼容
以下是我提出的解决方案:
- 删除该属性。这有效,但我收到警告'-myTextFieldSomethingHappened:'在协议中找不到
- 完全删除协议。没有警告,但如果您忘记在委托中实现协议,您也会丢失语义警告。
有没有办法定义委托属性以使编译器满意?
Some code I inherited has an annoying warning. It declares a protocol and then uses that to specify the delegate
@protocol MyTextFieldDelegate;
@interface MyTextField: UITextField
@property (nonatomic, assign) id<MyTextFieldDelegate> delegate;
@end
@protocol MyTextFieldDelegate <UITextFieldDelegate>
@optional
- (void)myTextFieldSomethingHappened:(MyTextField *)textField;
@end
Classes which use myTextField
implement the MyTextFieldDelegate
and are called it with this code:
if ([delegate respondsToSelector:@selector(myTextFieldSomethingHappened:)])
{
[delegate myTextFieldSomethingHappened:self];
}
This works, but creates the (legitimate) warning: warning: property type 'id' is incompatible with type 'id' inherited from 'UITextField'
Here are the solutions I've come up with:
- Remove the property. This works but I get the warning '-myTextFieldSomethingHappened:' not found in protocol(s)
- Drop the protocol entirely. No warnings, but you also lose the semantic warnings if you forget to implement the protocol in the delegate.
Is there a way to define the delegate property such that the compiler is happy?
发布评论
评论(4)
尝试:
try:
UITextField 还具有名为 委托,但它有另一种类型。只需将您的
delegate
属性重命名为其他名称即可。UITextField has also got property named delegate, but it has another type. Just rename your
delegate
property to something else.在 UITableView.h 中找到了答案。
UIScrollView 有属性名称 delegate,UITableView 有相同名称的属性。
Found the answer in UITableView.h.
The UIScrollView has property name delegate, and the UITableView has the same name property.
最初的问题是在声明 delegate 属性时没有有关 MyTextFieldDelegate 继承的信息。这是由协议的前向声明(@protocol MyTextFieldDelegate;)引起的。
我遇到了同样的问题,但在另一个 .h 文件中声明了协议。就我而言,解决方案只是 #import 适当的标头。
在你的情况下,你只需要交换声明的顺序:
The original problem is that there is no information about MyTextFieldDelegate's inheritance during declaration of delegate property. It's caused by forward declaration of protocol (@protocol MyTextFieldDelegate;).
I've faced the same problem but with protocol declaration in the other .h file. In my case solution was just to #import appropriate header.
In your case you just need to swap the order of declaration: