例如:
// ClassA.h
#import "ClassB.h"
@interface ClassA : NSObject
@property (nonatomic, readonly, strong) ClassB *classB;
@end
// ClassB.h
@interface ClassB : NSObject
@property (assign) CGFloat someProperty;
@end
// main.m
#import "ClassA.h"
...
ClassA *classA = [ClassA new];
classA.classB.someProperty
...
我想像main.m
中的classA.classB.someProperty
一样访问someProperty
,所以我必须导入ClassB。
。但我只想访问 ClassA
头文件中的 hmain.m
中 ClassB 的属性或方法,我想禁止用户在 main.m
中创建 ClassB 对象。
我该怎么办?
// main.m
classA.classB.someProperty --> ok
ClassB *classB = [ClassB new] --> forbid
最佳答案
如果想通过classA
获取classB
的属性,则必须导入ClassA
。
编辑
如果您不想在 main.m
中创建 classB
,则应在 classA.m
中导入 ClassB。 h
不在 classA.h
中。
演示
我创建了 2 个 Controller 类:ViewController
和 ViewController2
:
在 ViewController.h 中:
#import <UIKit/UIKit.h>
// Forward declare ViewController2, instead of importing it.
// This way it will be visible for your header file, but will get error if trying to create a instance of it
@class ViewController2;
@interface ViewController : UIViewController
@property (nonatomic, strong, readwrite) ViewController2 *vc2;
@end
在 ViewController.m 中:
#import "ViewController.h"
#import "ViewController2.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.vc2 = [[ViewController2 alloc] init];
}
@end
关于ios - 如何在iOS中访问对象(只读)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41285278/