首页 > IOS 子类对父类的属性修改必须在viewDidLoad函数中进行,否则该属性值将为nil

IOS 子类对父类的属性修改必须在viewDidLoad函数中进行,否则该属性值将为nil

我是弄了一个有公用组件的viewcontroller类作为基类,其他使用到该组件的类作为其子类。但是IOS 子类对父类的属性修改必须在viewDidLoad函数中进行,否则该属性值将为nil。
不知道是什么原因所致,求各位大大帮忙解决下
```object-c
//ViewController作为基类
ViewController.h

import <UIKit/UIKit.h>

define kWidth [UIScreen mainScreen].bounds.size.width

define kHeight [UIScreen mainScreen].bounds.size.height

@interface ViewController : UIViewController

@property (nonatomic,strong)UINavigationItem *navi;
@property (nonatomic,strong)UIButton *barButton;
@property (strong,nonatomic)UIButton *bButton;

-(void)goBack:(id)sender;
-(void)addChose:(id)sender;
@end
ViewController.m

import "ViewController.h"

import "SubViewController.h"

define kWidth [UIScreen mainScreen].bounds.size.width

define kHeight [UIScreen mainScreen].bounds.size.height

@interface ViewController ()

@end
@implementation ViewController

}
-(void)goBack:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)addChose:(id)sender{
SubViewController * sub = [[SubViewController alloc]init];
[self presentViewController:sub animated:YES completion:nil];
}
@end

//SubViewController.h作为子类
SubviewController.h

import "ViewController.h"

@interface SubViewController : ViewController
@end
SubviewController.m

import "SubViewController.h"

define kWidth [UIScreen mainScreen].bounds.size.width

define kHeight [UIScreen mainScreen].bounds.size.height

@interface SubViewController ()

@end

@implementation SubViewController

如果将属性修改作为一个函数放在外面就会出现错误结果,代码如下,结果如图所示:
SubviewController.m

加断点调试发现:self.navi = nil,不知道原因,调试截图如下:


SubviewController中的-(void)initView 方法名不要和父类的-(void)initView 方法重名。


问题的原因是因为我的”属性“其实是局部变量,在函数的内部的变量,在函数外面就变为nil了。


对父类属性的修改肯定子类的任何方法里面都可以进行更改啊。你可以参照一下ViewController的生命周期,看看你获取属性时,你重载的方法是否已经执行了。要不然你不会是忘了调用super xxxmethod了吧

【热门文章】
【热门文章】