Objective c 仅类及其子类的属性

Objective c 仅类及其子类的属性,objective-c,properties,protected,instance-variables,Objective C,Properties,Protected,Instance Variables,是否可以定义仅对其所定义的类以及该类的子类可用的属性 换句话说,有没有定义受保护属性的方法?从技术上讲,没有。属性实际上只是方法,所有方法都是公共的。我们在Objective-C中“保护”方法的方式是不让其他人知道它们 实际上,是的。您可以在类扩展中定义属性,并且仍然在主实现块中合成它们。您可以在子类实现中使用这种语法 @interface SuperClass (Internal) @property (retain, nonatomic) NSString *protectedString

是否可以定义仅对其所定义的类以及该类的子类可用的属性


换句话说,有没有定义受保护属性的方法?

从技术上讲,没有。属性实际上只是方法,所有方法都是公共的。我们在Objective-C中“保护”方法的方式是不让其他人知道它们


实际上,是的。您可以在类扩展中定义属性,并且仍然在主实现块中合成它们。

您可以在子类实现中使用这种语法

@interface SuperClass (Internal)

@property (retain, nonatomic) NSString *protectedString;

@end

这可以通过使用包含在基类和子类的实现文件中的类扩展名(而不是类别)来实现

类扩展的定义类似于类别,但没有类别名称:

@interface MyClass ()
在类扩展中,您可以声明属性,这将能够合成支持IVAR(XCode>4.4 IVAR的自动合成在这里也起作用)

在扩展类中,您可以重写/优化属性(将readonly更改为readwrite等),并添加对实现文件“可见”的属性和方法(但请注意,属性和方法不是真正私有的,仍然可以由选择器调用)

其他人建议为此使用单独的头文件MyClass_protected.h,但也可以在主头文件中使用
\ifdef
这样做:

例如:

基类.h

基类.m

儿童班

儿童班

当您调用
#import
时,它基本上会将.h文件复制粘贴到您要导入它的位置。 如果您有一个
#ifdef
,则只有在设置了带有该名称的
#define
时,它才会将代码包含在其中

在.h文件中,您没有设置define,因此任何导入此.h的类都不会看到受保护的类扩展名。
在基类和子类.m文件中,在使用
#导入
之前使用
#定义
,这样编译器将包含受保护的类扩展。

您可以使用类别来达到目的

@interface SuperClass (Protected)

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *topMenuView;
@property (nonatomic, strong) UIView *bottomMenuView;

@end

在子类中,您将该类别导入文件.m

中以“保护”类扩展接口需要位于单独的头文件中才能包含在类及其子类中。据我所知,基类接口扩展中声明的任何属性对子类都不可用——它们的作用域是私有的,不受保护。请看下面的讨论:@Harkonian如果您自己声明选择器,您可以随时调用它。除了简单地隐藏其声明之外,没有“保护”方法的事情。Objective-C没有受保护或私有方法的概念。仅受保护或私有IVAR。
// this will import BaseClass.h
// with BaseClass_protected defined,
// so it will also get the protected class extension

#define BaseClass_protected
#import "BaseClass.h"

@implementation BaseClass

-(void)baz {
    self.foo = @"test";
    self.bar = 123;
}

@end
// this will import BaseClass.h without the class extension

#import "BaseClass.h"

@interface ChildClass : BaseClass

-(void)test;

@end
// this will implicitly import BaseClass.h from ChildClass.h,
// with BaseClass_protected defined,
// so it will also get the protected class extension

#define BaseClass_protected 
#import "ChildClass.h"

@implementation ChildClass

-(void)test {
    self.foo = @"test";
    self.bar = 123;

    [self baz];
}

@end
@interface SuperClass (Protected)

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *topMenuView;
@property (nonatomic, strong) UIView *bottomMenuView;

@end