是否有可能定义在类及其子类中可用的属性,也就是说,是否有一种方法定义受保护的属性?
是否有可能定义在类及其子类中可用的属性,也就是说,是否有一种方法定义受保护的属性?
从技术上讲,不是私有的。属性实际上只是方法,而所有方法都是公共的。在 Objective-C 中“保护”方法的方式是不让其他人知道它们。
实际上,可以通过在类扩展中定义属性,然后在主要的实现块中使用 @synthesize
来实现私有属性。
@interface MyClass ()
#ifdef
进行如下操作:@interface BaseClass : NSObject
// foo is readonly for consumers of the class
@property (nonatomic, readonly) NSString *foo;
@end
#ifdef BaseClass_protected
// this is the class extension, where you define
// the "protected" properties and methods of the class
@interface BaseClass ()
// foo is now readwrite
@property (nonatomic, readwrite) NSString *foo;
// bar is visible to implementation of subclasses
@property (nonatomic, readwrite) int bar;
-(void)baz;
@end
#endif
BaseClass.m
// 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
ChildClass.h
// this will import BaseClass.h without the class extension
#import "BaseClass.h"
@interface ChildClass : BaseClass
-(void)test;
@end
ChildClass.m
// 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
#import
时,它基本上将.h文件复制粘贴到你导入它的位置。
如果你有一个#ifdef
,它只会包含该名称的#define
被设置时内部的代码。#define
在使用#import
之前,以便编译器将包括受保护的类扩展。@interface SuperClass (Internal)
@property (retain, nonatomic) NSString *protectedString;
@end
你可以使用分类来达到你的目的
@interface SuperClass (Protected)
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *topMenuView;
@property (nonatomic, strong) UIView *bottomMenuView;
@end