2010-07-31 62 views
17

我想定义一个具有很少属性的协议,并且需要在另一个NSObject子类中使用这些属性。请给我链接或示例代码。我需要这个与10.5一起工作。如何在协议中定义和实现属性

感谢 请检查下面的示例代码

@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体系Compling代码工作正常。但是,错误,如果我会改的架构是i386,然后我得到以下警告:

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 

我只是想知道为什么它与@synthesize x86_64的,而不是在I386工作**

回答

33

@property只是对编译器说,该类需要定义匹配该属性的方法。

@protocol MyProtocol 
@property (nonatomic, readonly) id someObject; 
@property (nonatomic, getter=isAlive) BOOL alive; 
@end 

任何执行该协议,现在需要有

- (id)someObject; 
- (BOOL)isAlive; 
- (void)setAlive:(BOOL)aBOOL; 
+9

合成属性也应该起作用,因为它指示编译器提供访问器方法实现。 – 2010-07-31 12:36:27

+0

谢谢,如果我将项目体系结构保留为x86_64,则您提供的代码完美工作。如果我将体系结构更改为i386,则会收到以下警告: MyCustomClass.m:13:错误:合成属性'someObject'必须与兼容的ivar命名相同或必须明确命名为ivar 错误:合成属性'alive'必须被命名为相同的ivar,或者必须明确命名ivar 我只想知道为什么它在x86_64中使用@synthesize而不是在i386中。 谢谢 – AmitSri 2010-07-31 12:39:01

+0

如果可能,我想尽量少写代码。还请解释一下不同体系结构之间的区别以及我想选择编译应用程序的区别。 – AmitSri 2010-07-31 12:45:44

1

我认为你正在处理的事情是引进Objective-C 2.0的主要副作用。它可以让你做一些事情,比如声明属性而不用定义实例变量。但是(正如你所发现的那样),它只有x86_64和10.5之后的兼容性。

+0

我有类似的错误。我检查了x86_64的“仅构建主动架构”框。它修复了它。 – user523234 2011-05-19 12:00:06