Objective C 半只读属性

Abd*_*mad 1 properties objective-c readonly ios

我想在我的类中声明 a public NSString propertyclassreadonly property在我的班级之外充当,但我可以assign在我的班级内对其进行任何赋值。我怎样才能实现这种行为。

Gop*_*ath 5

你必须.h像这样在文件中声明你的财产

@interface MyClass : NSObject

@property (strong, nonatomic, readonly) NSString *aString;

@end
Run Code Online (Sandbox Code Playgroud)

但在你的.m文件中你必须有

@interface MyClass () // your anonymous category

@property (strong, nonatomic, readwrite) NSString *aString;

@end

@implementation MyClass

@end
Run Code Online (Sandbox Code Playgroud)

在外部aStringreadonly,在内部您可以设置值(readwrite)

你是通过实施一个 anonymous category also known as class extension in Objective-C