我看到Objective-C协议的使用方式如下:
@protocol MyProtocol <NSObject>
@required
@property (readonly) NSString *title;
@optional
- (void) someMethod;
@end
我见过使用这种格式来代替编写子类扩展的具体超类.问题是,如果你遵守这个协议,你需要自己合成属性吗?如果你要扩展一个超类,答案显然是否定的,你不需要这样做.但是如何处理协议需要符合的属性呢?
据我所知,您仍然需要在符合需要这些属性的协议的对象的头文件中声明实例变量.在这种情况下,我们能假设它们只是一个指导原则吗?显然,对于所需的方法,情况并非如此.编译器会因为你排除了协议列出的一个必需方法而责骂你.然而,房地产背后的故事是什么?
下面是一个生成编译错误的示例(注意:我对代码进行了裁剪,但没有考虑当前的问题):
我的协议.H
@protocol MyProtocol <NSObject>
@required
@property (nonatomic, retain) id anObject;
@optional
TestProtocolsViewController.H
- (void)iDoCoolStuff;
@end
#import <我的协议.H>
@interface TestProtocolsViewController : UIViewController <MyProtocol> {
}
@end
TestProtocolsViewController.M
#import "TestProtocolsViewController.H"
@implementation TestProtocolsViewController
@synthesize anObject; // anObject doesn't exist, even though we conform to MyProtocol.
- (void)dealloc {
[anObject release]; //anObject doesn't exist, even though we conform to MyProtocol.
[super dealloc];
}
@end