首页 > 解决方案 > Objective-c 从子类获取基类属性

问题描述

我在 .h 文件中创建了 @property(例如 BOOL 值)。在 .m 文件中,我更改了 BOOL 值。

在子类代码中,我想获取此属性的NSLog(@"%@", _value)值,但值始终为空。

基类代码:

.h 文件:

@interface CommonViewController : UIViewController <MPPGraphDelegate, MPPInputSourceDelegate>

...

@property(nonatomic) BOOL buttonState;

@property(nonatomic) UIButton* button;

...

@end

.mm 文件:

- (void)viewDidLoad {
  [super viewDidLoad];
   ...

    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button addTarget:self
                       action:@selector(aMethod:)
                       forControlEvents:UIControlEventTouchUpInside];
    [_button setTitle:@"Show View" forState:UIControlStateNormal];
    _button.frame = CGRectMake(100, 500, 120, 30);
    [self.view addSubview:_button];
}

-(void)aMethod:(UIButton*) sender {
    if (sender.isSelected) {
        sender.selected = NO;
        _buttonState = NO;  <-- change value
    } else {
        sender.selected = YES;
        _buttonState = YES;  <-- change value
    }
}

子类代码

.h 文件:

@interface HandTrackingViewController : CommonViewController
...
@end

.mm 文件:

@implementation HandTrackingViewController

@synthesize buttonState = _buttonState;
- (void)someMethod {
      NSLog(_buttonState ? @"YES" : @"NO"); <-- _buttonState always null
}

@end

标签: objective-c

解决方案


self.buttonState没有@synthesize解决我的问题


推荐阅读