2

我已经阅读了The Objective-C Programming Language文档中的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关键字是否产生以下代码:

// 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声明的复制属性不是必需的,因为那里不需要setter,但我们必须指定它与第二个属性重新声明一致。我的想法对吗?

4

1 回答 1

3

是的,你的理解是正确的。

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.

于 2011-09-27T08:52:29.197 回答