更新时间:2022-06-25 03:48:09
最简单的方法是在 MyClass
的公共接口中将属性声明为 readonly
(即 .h 文件):
The easiest way to accomplish this is to declare the property as readonly
in the public interface for MyClass
(i.e. the .h file):
@property (readonly) NSInteger prop;
然后,在该类的 .m 文件中,声明一个类 extension(名称为空的类别).在类扩展中,您可以 重新声明@property 以将其可写性更改为可读写:
Then, in .m file for that class, declare a class extension (a category with an empty name). In class extensions, you may redeclare a @property to change its writeability to readwrite:
@interface MyClass ()
@property (readwrite) NSInteger prop;
@end
@implementation MyClass
@synthesize prop;
...
@end
当然,Objective-C 并没有强制执行访问限制,所以没有什么可以阻止一些流氓代码调用 -[MyClass setProp:]
.然而,编译器会将其标记为警告,这与您在 Objective-C 中所能获得的一样好.不幸的是,没有标准的方法可以将这个受保护的"可写属性记录到子类中;您必须为您的团队确定一个约定,或者如果它在您要发布的框架中,则将其放入课程的公共文档中.
Of course, Objective-C does not enforce access restrictions, so there's nothing stopping some rogue code from calling -[MyClass setProp:]
. The compiler will flag this as a warning, however, which is as good as you can get in Objective-C. Unfortunately, there is no standard way to document this "protected" writeable property to subclasses; you'll have to settle on a convention for your team and or put it in the public documentation for the class if it's in a framework that you're going to release.