1

我正在学习客观的 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

谢谢你。(对不起我的英语不好)

4

2 回答 2

2

Objective-C 不提供受保护的方法/属性。看到这个问题。

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

于 2012-06-12T13:30:00.807 回答
0

只要您使用带有下划线前缀的相同名称,您就可以为该属性手动创建 ivar:

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

这使得属性@protected(默认为@private)的合成ivar,然后子类可以直接使用超类的ivar。

于 2013-04-05T15:00:43.527 回答