【发布时间】:2014-09-04 14:21:56
【问题描述】:
我有一个名为 OnSuggestionTextChanged
的简单协议@protocol OnSuggestionTextChanged <NSObject>
-(void)onTextChanged:(NSString*)newText;
@end
我还有另一个称为 TextEditable 的协议,它具有此协议作为属性
#import <Foundation/Foundation.h>
#import "OnSuggestionTextChanged.h"
@protocol TextEditable <NSObject>
@required
-(void)setTextString:(NSString*)text;
-(NSString*)textString;
-(void)notifySuggestionButtonPressed;
-(NSInteger)cursorPosition;
@property(nonatomic,weak)id<OnSuggestionTextChanged> onSuggestionTextChange;
@end
但是在我的自定义UITextView 中,它符合TextEditable 协议。
当我尝试访问属性OnSuggestionTextChanged
我得到一个:
[CustomTextView onSuggestionTextChanged] 的选择器无法识别 (不是 for onTextChanged)
这真的很奇怪,因为 Xcode 不会抛出编译器错误而是运行时错误。
您能否告诉我我正在尝试做的事情是否真的可行。如果是这样,为什么我会得到无法识别的选择器?
以防万一你们不相信我。
【问题讨论】:
-
如果协议包含
@property,那么NOT 是否意味着该属性现在是所有实现类的一部分。相反,在遵守协议的类(如您的UITextView子类)中,您有责任确保该属性存在。请参阅:stackoverflow.com/a/844785/88111 此外,正如@rmaddy 下面提到的,将@synthesize添加到您的子类应该会为您生成getter/setter。 -
在符合
TextEditable协议的类中,尝试添加@synthesize onSuggestionTextChange;。 -
在协议中使用属性是不好的做法。你应该重新考虑你的协议。
-
顺便说一句。我检查过。 Xcode 抛出编译器警告:
Auto property synthesis will not synthesize property declared in a protocol. -
您需要为该属性实现 setter 和 getter,例如使用
@synthesize,如果默认的对你来说足够好的话。如果没有,你仍然可以实现自己的。
标签: ios objective-c