如何在iOS中访问对象(readonly)的属性

时间:2016-12-22 14:21:42

标签: ios objective-c

例如:

// 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
...

我想在someProperty中访问classA.classB.someProperty main.m,因此我必须在ClassB.h头文件中导入ClassA。但我只想在main.m中访问ClassB的属性或方法,我想禁止用户在main.m中创建 ClassB 对象。 我该怎么办?

// main.m
classA.classB.someProperty --> ok
ClassB *classB = [ClassB new] --> forbid

2 个答案:

答案 0 :(得分:2)

如果您想通过classB获取classA的属性,则必须导入ClassA

修改

如果您不想在classB中创建main.m,则应该classA.m导入ClassB.h而不是classA.h

<强>演示

我创建了2个控制器类:ViewControllerViewController2

在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

答案 1 :(得分:0)

- (instancetype)init NS_UNAVAILABLE;

您可以通过这种方式添加归因于NS_UNAVAILABLE init ClassB方法的ClassB *classB = [ClassB new]; ,您将无法拨打电话,

{{1}}