2012-06-12 38 views
1

我正在学习Objective C语言,我问一个简单的问题, 当我做到这一点:属性公共和私人但不受保护?

// ParentClass.h 
@interface ParentClass : NSObject 
@property (read, strong) NSString *parentPublicStr; 
@end 

// ParentClass.m 
@interface ParentClass() 
@property (readwrite, strong) NSString *parentPrivateStr; 
@end 

@implementation ParentClass 
@synthesize parentPublicStr; 
@synthesize parentPrivateStr; 
@end 

// Subclass SubClass.h 
@interface SubClass : ParentClass 
- (void) test; 
@end 

@implementation SubClass 
- (void) test 
{ 
// Its not possible to do that : [self setParentPrivateStr:@"myStrin"] 
// And for parentPublicStr, it is public property so not protected, because i can change the value 
// in main.c, and it's so bad.. 
} 
@end 

我想创建一个受保护的属性:X

THX你。 (对不起,我的英语)

+0

[Objective-C - Private vs Protected vs Public]可能的重复(http://stackoverflow.com/questions/4869935/objective-c-private-vs-protected-vs-public) –

回答

2

Objective-C不提供受保护的方法/属性。问题见this

编辑:另请参阅this的答案。您仍然可以通过在类扩展中声明属性并在子类中包含扩展来练习封装。

+0

thx you for answer: ) – helock

0

您可以手动,只要您使用下划线前缀相同的名称创建属性伊娃:

@interface ParentClass : NSObject 
{ 
    @protected 
    NSString* _parentPublicStr; 
} 
@property (read, strong) NSString *parentPublicStr; 
@end 

这使得对@protected属性的合成伊娃(默认为@private)和子类可以直接使用超类'ivar。