OK basically I have a class in an iPhone app where I want it to some read only propertys. Meaning that the owning class can read and write the property, but other objects can only read it. I try the "readonly" option when I declare the property, but then my class can't even write it. What use is that?
5 回答
假设您想在您的类中创建一个名为foo
an的属性。int
YourClass
在您的界面 (.h) 文件中执行此操作:
@property(readonly) int foo;
然后在您的实现 (.m) 文件中,设置一个类扩展名,您可以在其中重新定义您的属性。
@interface YourClass()
@property(readwrite) int foo;
@end
这导致财产是readonly
公开的,但readwrite
私人的。
然后,当然,您foo
在随后的实现中进行综合。
@synthesize foo;
如果不是太不方便,只需使用类中的 ivar 或“支持”变量来修改值。像这样:
在您的 .h 文件中:
@interface ClassName
@property (readonly,nonatomic) NSInteger readOnlyValue;
@end
在您的 .m 文件中:
@implementation ClassName
@synthesize readOnlyValue = _readOnlyValue;
_readOnlyValue = 42;
@end
虽然您可以按照其他答案中所述的方式直接访问 iVar,但更好的解决方案通常是使用类扩展。它们的设计正是为了解决这个问题,并且通过使用它们,您可以在以后轻松地重构您的代码,以便在您的应用程序中向其他类公开 的readwrite
定义,@property
而无需将其公开给所有类。
前段时间我写了一个详细的解释。
You can implement your own setter in the .m class or synteshize as: foo = _foo; so you can call _foo (private variable) internally
进一步思考,实现这一点的最简单方法是在类扩展中添加一个普通属性,然后只在标题中声明 getter。例如
界面:
@interface MyClass: NSObject
- (NSString *)someString;
@end
执行:
@interface MyClass ()
@property (nonatomic, retain) NSString *someString;
@end
@implementation MyClass
@synthesize someString;
@end
您将能够使用点符号或其他方式获取和设置,并直接访问someString
类中的实例变量,并且看到接口的每个人都可以使用点符号或其他方式获取。