【发布时间】:2012-06-18 07:51:38
【问题描述】:
我一直试图找到一种解决方法来在 Objective-C 中声明 @protected 属性,这样只有层次结构中的子类才能访问它们(只读,不能写)。 我读到没有记录的方法可以做到这一点,所以我想到了这个解决方法,我想问问 StackOverflow 对此的看法。
层次结构顶部的每个自定义类都包含三个类,一个实现和两个接口。 让我们为它们命名:
ClassA.h
ClassA_protected.h
ClassA.m
那么这个 ClassA 的任何子类都会像往常一样:
ClassB.h
ClassB.m
首先,我创建了接口 ClassA.h,在其中声明了一个受保护的 int 变量,以便 ClassA 的任何子类都可以访问它:
@interface ClassA : NSObject{
@protected
int _myProtectedInt;
}
@end
下一步是我所说的解决方法。但是,一旦您阅读它,您会发现它非常简单。我声明了第二个名为 ClassA_protected.h 的接口,它实际上作为 ClassA.h 的 extension 工作,并允许我们将属性标记为 readonly:
#import "ClassA.h"
@interface ClassA ()
@property (nonatomic , readonly) int myProtectedInt;
@end
准备受保护层次结构的最后一步是在 ClassA.m 中声明它的实现,我们只合成我们的属性:
#import "ClassA_protected.h"
@implementation ClassA
@synthesize myProtectedInt = _ myProtectedInt;
@end
这样,每个需要成为 ClassA.h 子类的类都将导入 ClassA_protected.h。因此,像 ClassB.h 这样的孩子将如下所示:
#import "ClassA_protected.h"
@interface ClassB : ClassA
@end
以及从 ClassB.m 的实现中访问此属性的示例:
@implementation ClassB
-(void) method {
//edit protected variable
_myProtectedInt= 1;
//normal access
self.muProtectedInt;
}
@end
【问题讨论】:
-
如果我将“ClassA_protected.h”导入到仅访问 ClassB 的 ViewController 类中怎么办?我仍然可以通过主类中的 ClassB 对象访问 ClassA 的受保护属性(这里是 ViewController 类)。
标签: objective-c properties protected