Readonly public property redeclared as readwrite i

2019-04-13 06:09发布

问题:

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

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

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?

回答1:

Yes, your understanding is correct.

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.