2

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?

4

5 回答 5

7

假设您想在您的类中创建一个名为fooan的属性。intYourClass

在您的界面 (.h) 文件中执行此操作:

@property(readonly) int foo;

然后在您的实现 (.m) 文件中,设置一个类扩展名,您可以在其中重新定义您的属性。

@interface YourClass()

@property(readwrite) int foo;

@end

这导致财产是readonly公开的,但readwrite私人的。

然后,当然,您foo在随后的实现中进行综合。

@synthesize foo;
于 2012-04-13T21:52:19.740 回答
3

如果不是太不方便,只需使用类中的 ivar 或“支持”变量来修改值。像这样:

在您的 .h 文件中:

@interface ClassName

@property (readonly,nonatomic) NSInteger readOnlyValue;

@end

在您的 .m 文件中:

@implementation ClassName

@synthesize readOnlyValue = _readOnlyValue;



_readOnlyValue = 42;

@end
于 2012-04-13T21:39:18.747 回答
2

虽然您可以按照其他答案中所述的方式直接访问 iVar,但更好的解决方案通常是使用类扩展。它们的设计正是为了解决这个问题,并且通过使用它们,您可以在以后轻松地重构您的代码,以便在您的应用程序中向其他类公开 的readwrite定义,@property而无需将其公开给所有类。

前段时间我写了一个详细的解释。

于 2012-04-13T21:52:02.270 回答
0

You can implement your own setter in the .m class or synteshize as: foo = _foo; so you can call _foo (private variable) internally

于 2012-04-13T21:37:19.293 回答
0

进一步思考,实现这一点的最简单方法是在类扩展中添加一个普通属性,然后只在标题中声明 getter。例如

界面:

@interface MyClass: NSObject

- (NSString *)someString;

@end

执行:

@interface MyClass ()
@property (nonatomic, retain) NSString *someString;
@end

@implementation MyClass

@synthesize someString;

@end

您将能够使用点符号或其他方式获取和设置,并直接访问someString类中的实例变量,并且看到接口的每个人都可以使用点符号或其他方式获取。

于 2012-04-13T21:42:24.720 回答