ios - 如何在iOS中访问对象(只读)的属性

标签 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
...

我想像main.m中的classA.classB.someProperty一样访问someProperty,所以我必须导入ClassB。 ClassA 头文件中的 h 。但我只想访问 main.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 类: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

关于ios - 如何在iOS中访问对象(只读)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41285278/

相关文章:

iphone - iOS 将数据从 tableview 传递到新 View

ios - Swift 中的 UITableView - 单元格出队

ios - phonegap oauthio 插件不会加载

objective-c - 如何在 IOS6 中的全屏模式 MPMoviePlayerController 上添加滑动手势

iphone - 看不出为什么这里有内存泄漏

ios - 我真的需要单例上的共享实例吗?

objective-c - Decimal 在 Swift 3 中作为 NSDecimal 而不是 NSDecimalNumber 导入到 Objective C

iphone - 在后台运行时间间隔计算

ios - 在 Storyboard中嵌套 View Controller

iOS - 多个 http 请求 - 在获取所有内容后做一些事情