内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我已经看到Objective-C协议的使用以如下方式使用:
@protocol MyProtocol <NSObject>
@required
@property (readonly) NSString *title;
@optional
- (void) someMethod;
@end
我已经看过使用这种格式,而不是编写一个子类扩展的具体超类。问题是,如果你符合这个协议,你是否需要自己综合属性?如果你正在扩展一个超类,答案显然不是,你不需要。但是,如何处理协议要求符合的属性呢?
根据我的理解,您仍然需要在符合需要这些属性的协议的对象的头文件中声明实例变量。那么,我们可以假设他们只是一个指导原则吗?对于所需的方法来说,情况并非如此。编译器将会排除手腕,排除协议列出的必需方法。属性背后的故事是什么?
下面是一个例子,它会产生一个编译错误(注意:我已经修剪了那些没有反映出问题的代码):
MyProtocol.h
@protocol MyProtocol <NSObject>
@required
@property (nonatomic, retain) id anObject;
@optional
TestProtocolsViewController.h
- (void)iDoCoolStuff;
@end
#import <MyProtocol.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
该协议只是通过协议告诉每个知道你的课程的人,该财产anObject
将在那里。协议并不是真实的,它们本身没有变量或方法 - 它们只描述了关于你的类的一组特定的属性,因此持有对它们的引用的对象可以以特定的方式使用它们。
这意味着在你的课堂中符合你的协议,你必须尽一切努力确保anObject正常工作。
@property
并且@synthesize
在心脏的两个机制为你生成代码。 @property
只是说这个属性名称会有一个getter(和/或setter)方法。@property
仅这些日子就足以让系统为你创建方法和存储变量(您以前必须添加@sythesize
)。但是你必须有一些东西来访问和存储变量。
下面是我的一个很好的例子,首先是协议定义:
@class ExampleClass;
@protocol ExampleProtocol
@required
// Properties
@property (nonatomic, retain) ExampleClass *item;
@end
以下是支持此协议的类的一个工作示例:
#import <UIKit/UIKit.h>
#import "Protocols.h"
@class ExampleClass;
@interface MyObject : NSObject <ExampleProtocol> {
// Property backing store
ExampleClass *item;
}
@implementation MyObject
// Synthesize properties
@synthesize item;
@end