【发布时间】:2014-09-09 13:25:41
【问题描述】:
我想在我的class 中声明一个public NSString property,它在我的课堂外充当readonly property,但我可以在我的课堂内使用assign 任何值。我怎样才能实现这种行为。
【问题讨论】:
标签: ios objective-c properties readonly
我想在我的class 中声明一个public NSString property,它在我的课堂外充当readonly property,但我可以在我的课堂内使用assign 任何值。我怎样才能实现这种行为。
【问题讨论】:
标签: ios objective-c properties readonly
您必须像这样在.h 文件中声明您的属性
@interface MyClass : NSObject
@property (strong, nonatomic, readonly) NSString *aString;
@end
但是在你的.m 文件中你必须有
@interface MyClass () // your anonymous category
@property (strong, nonatomic, readwrite) NSString *aString;
@end
@implementation MyClass
@end
在外部aString 是readonly,在内部你可以设置值(readwrite)。
您通过实现anonymous category also known as class extension in Objective-C 来实现它
【讨论】:
private category,提问者可以在其中进一步了解它。
NSStrings 没有正确声明——它们应该是指针。
private category这个词已经在stackoverflow的答案和一些高级的Objc书籍中广泛使用。
在标头中将属性定义为readonly,并在class extension 的实现文件中将其声明为readWrite。该属性在类实现之外是只读的,在实现中是读/写的。
// Interface file:
@interface Test : NSObject
@property (nonatomic, copy, readonly) NSString *propertyString;
@end
// Implementation file:
@interface Test () // Class Extension
@property (nonatomic, copy, readwrite) NSString *propertyString;
@end
@implementation Test
@end
见:Use Class Extensions to Hide Private Information
正如@Amin Negm-Awad 在回答中指出的那样:接口和类扩展不需要在接口或实现文件中,尽管这是通常的用法。
【讨论】:
在.h文件中添加:
@property(nonatomic,readonly)NSString* property;
在.m文件中添加:
@interface yourClass ()
@property(nonatomic,readwrite)NSString* property;
@end
【讨论】:
在头文件(接口)中将属性定义为只读,在实现文件中定义为读写。这也使您可以轻松地使其变弱/变强/复制。
【讨论】:
这可能很明显:
在您的 .h 文件中将属性声明为 readonly
@property (nonatomic, assign, readonly, getter = isLoading) BOOL loading;
在您的 .m 文件中将属性声明为 readwrite
@property (nonatomic, assign, readwrite, getter = isLoading) BOOL loading;
这是一个例子,显然你应该创建强大的NSString 属性,并且我假设编译器不允许在类之外设置其他值,但在它内部会。
【讨论】:
除了告诉您定义只读属性并将其更改为读写属性的现有答案之外,这是完全正确的预期模式(即读写的用途),我想添加一个可能重要的信息:
您将只读定义放在接口中。 (不是标题!)
您将读写定义放在类延续中。 (不是实现文件)
有人可能会说这是一样的,因为接口驻留在头文件中,而类延续驻留在实现文件中。但这只是通常的情况。
您还可以将类延续放在第三个文件中。然后像“朋友类”这样的东西可以额外导入它,这个“炒类”有写访问权。在开发框架时,我经常这样做。
MyClass.h: // 公共标头,所有人都可以使用
@interface MyClass : NSObject
@property (readonly, …) id property1; // Everyone can read it
@property (readonly, …) id property2; // Everyone can read it
- (void)method; // Everyone can use it
@end
MyClass_Package.h: // 项目头,框架类可用,框架用户不可用
@interface MyClass()
@property (readwrite, …) id property1; // All classes inside the framework can write it
- (void)packageMethod; // All classes inside the framework can use it
@end
MyClass.m
@interface MyClass() // A second class extension inside .m
@property (readwrite, …) id property2; // Only MyClass can write it
- (void)privateMethod; // Only MyClass can use it
@end
【讨论】:
class continuation。
在头部定义属性为readonly,并使用下划线语法设置。
@property (nonatomic, readonly) NSString *myString;
- (void)someMethodInYourDotMFile {
_myString = YES;
}
【讨论】: