Syntax for resolving incompatible property type on

2019-04-20 01:48发布

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:

  1. Remove the property. This works but I get the warning '-myTextFieldSomethingHappened:' not found in protocol(s)
  2. 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条回答
女痞
2楼-- · 2019-04-20 02:14

Found the answer in UITableView.h.

The UIScrollView has property name delegate, and the UITableView has the same name property.

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>
// Your code
......

@end
查看更多
我命由我不由天
3楼-- · 2019-04-20 02:18

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:

@class MyTextField;

@protocol MyTextFieldDelegate <UITextFieldDelegate>
@optional
- (void)myTextFieldSomethingHappened:(MyTextField *)textField;
@end

@interface MyTextField : UITextField
@property (nonatomic, assign) id <MyTextFieldDelegate> delegate;
@end
查看更多
聊天终结者
4楼-- · 2019-04-20 02:19

UITextField has also got property named delegate, but it has another type. Just rename your delegate property to something else.

查看更多
做个烂人
5楼-- · 2019-04-20 02:23

try:

@property (nonatomic, assign) id<UITextFieldDelegate,MyTextFieldDelegate> delegate;
查看更多
登录 后发表回答