Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 公共和私人财产,但不受保护?_Objective C_Properties_Private_Public - Fatal编程技术网

Objective c 公共和私人财产,但不受保护?

Objective c 公共和私人财产,但不受保护?,objective-c,properties,private,public,Objective C,Properties,Private,Public,我正在学习objective C语言,我问了一个简单的问题, 当我这样做时: // ParentClass.h @interface ParentClass : NSObject @property (read, strong) NSString *parentPublicStr; @end // ParentClass.m @interface ParentClass () @property (readwrite, strong) NSString *parentPrivateStr; @

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


谢谢。(对不起,我说的是英语)

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


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

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

@interface ParentClass : NSObject
{
    @protected
    NSString* _parentPublicStr;
}
@property (read, strong) NSString *parentPublicStr;
@end
这使得属性@protected的合成ivar(默认值为@private)和子类可以直接使用超类的ivar。

可能的重复