如何在协议中定义和实现属性 [英] How to define and implement properties in protocol
问题描述
我想定义一个具有少量属性的协议,并需要在另一个NSObject子类中使用这些属性。请给我链接或示例代码。我需要使用10.5。
I want to define one protocol with few properties and need to use those properties in another NSObject subclass. Please give me link or example code. I need that to work with 10.5.
感谢
请检查以下样本代码
Thanks PLEASE CHECK THE FOLLOWING SAMPLE CODE
@protocol MyProtocol
@property (nonatomic, readonly) id someObject;
@property (nonatomic, getter=isAlive) BOOL alive;
@end
#import "MyProtocol.h"
@interface MyCustomClass : NSObject <MyProtocol>{
}
@end
#import "MyCustomClass.h"
@implementation MyCustomClass
@synthesize someObject,alive;
/*
- (id)someObject {
return nil;
}
- (BOOL)isAlive {
return YES;
}
- (void)setAlive:(BOOL)aBOOL {
}
*/
@end
**已添加:
使用x86_64架构的补充代码可以正常工作。但错误,如果我将改变架构到i386,然后我得到以下警告:
**Added: Compling code with x86_64 architecture works fine. But error if i'll change the architecture to i386, then i am getting following warnings:
MyCustomClass.m:13: error: synthesized property 'someObject' must either be named the same as a compatible ivar or must explicitly name an ivar
error: synthesized property 'alive' must either be named the same as a compatible ivar or must explicitly name an ivar
我只是想知道为什么它在x86_64中使用@synthesize而不是在i386 。**
I just want to know why it is working in x86_64 with @synthesize and not in i386.**
推荐答案
@property
类需要定义匹配该属性的方法。
@property
just says to the compiler that the class is expected to define the methods to match that property.
@protocol MyProtocol
@property (nonatomic, readonly) id someObject;
@property (nonatomic, getter=isAlive) BOOL alive;
@end
实施该协议的任何内容现在需要具有
Anything implementing that protocol will now need to have
- (id)someObject;
- (BOOL)isAlive;
- (void)setAlive:(BOOL)aBOOL;
这篇关于如何在协议中定义和实现属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!