只读公共属性在私有接口中重新声明为 readwrite .. 了解更多 [英] Readonly public property redeclared as readwrite in private interface.. understanding a bit more
问题描述
我已阅读Objective-C 编程语言 文档,我想请你们中的一些人向我澄清以下属性重新声明:
I've read the Property redeclaration chapter in The Objective-C Programming Language document and I'd like if some of you can clarify me the following property redeclaration:
// MyObject.h public header file
@interface MyObject : NSObject {
NSString *language;
}
@property (readonly, copy) NSString *language;
@end
// MyObject.m private implementation file
@interface MyObject ()
@property (readwrite, copy) NSString *language;
@end
@implementation MyObject
@synthesize language;
@end
我只是想了解上面的@property
和@synthesize
关键字是否产生以下代码:
I just want to understand if the above @property
and @synthesize
keywords produce the following code:
// MyObject.h public header file
@interface MyObject : NSObject {
NSString *language;
}
-(NSString *)language;
@end
// MyObject.m private implementation file
@interface MyObject ()
-(void)setLanguage: (NSString *) aString;
@end
@implementation MyObject
-(NSString *)language {
return language;
}
-(void)setLanguage: (NSString *) aString {
[language release];
language = [aString copy];
}
@end
所以,发生的事情是编译器看到第一个 @property
声明并在公共接口中添加了一个 getter 方法......然后,当涉及到实现文件时,它找到了另一个 @property
声明相同的属性,但在私有接口中具有 readwrite 属性,并且只添加了一个 setter 方法,因为 getter 已经添加到公共接口..然后,@synthesize
找到关键字并且两个实现都被添加到私有实现部分..第一个 @property
声明的复制属性不是必需的,因为那里不需要设置器,但我们必须指定它与第二次财产重新申报保持一致.我的想法对吗?
So, what happens is that the compiler sees the first @property
declaration and adds a getter method in the public interface... than, when it comes to the implementation file it finds another @property
declaration for the same property but with readwrite attribute within the private interface and adds only a setter method since the getter has been already added to the public interface.. then, the @synthesize
keyword is found and both implementations are added to the private implementation section.. the copy attribute of the first @property
declaration would not be necessary, since the setter is not needed there, but we must specify it to be consistent with the second property redeclaration. Are my thoughts right?
推荐答案
是的,你的理解是正确的.
Yes, your understanding is correct.
还要注意,Objective-C 中没有严格的私有方法.外部调用者仍然可以调用 setLanguage:
.编译器会输出警告,但消息会在运行时通过.
Also note that there are no strictly private methods in Objective-C. An external caller can still call setLanguage:
. The compiler will output a warning but the message would get through at runtime.
这篇关于只读公共属性在私有接口中重新声明为 readwrite .. 了解更多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!