ARC 分配实例变量 init 或 awakeFromNib
ARC assigning instance variable init or awakeFromNib
我试图在我的 init
方法中初始化一个变量,但它似乎在调用链到达 awakeFromNib
时被释放。我已经阅读了几个主题,而且太多的主题似乎都有同样的困惑 - 应该非常简单明了的东西...... :(.
- (id)init {
self = [super initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];
if (self) {
self.customObject = [CustomObject currentInstance]; //OK
}
}
- (void)awakeFromNib {
[self.customObject someMethod]; //here self.customObject is nil?
//self.customObject = [CustomObject currentInstance]; // Why should I do this here?
}
我的 .m
文件中的声明没什么特别的。我不想在不了解 背后的原因 的情况下在 awakeFromNib
中分配 属性。
@property (strong) CustomObject *customObject;
CustomObject实例化.m文件
static CustomObject customObject;
@implementation CustomObject {
+ (instancetype)initMockCustomObject {
customObject = (CustomObject*)[OCMockObject mockForClass:[CustomObject class]];
}
+ (instancetype)currentInstance {
if ( customObject == nil) { [NSException raise...]; }
return customObject;
}
}
initMockCustomObject
已在 AppDelegate 中调用。
编辑:在 init
中添加了对 initWithNibName
方法的实际超级调用。
Edit2:添加了单例实例
感谢您的意见。我创建了一个绝对最小的沙盒项目,我发现我的一个父 NIB 中有一个对象,它与 MyViewController 的类型相同,导致了这个问题。关闭这个问题,因为它太特定于应用程序。 init中初始化变量的基本问题就OK了
我试图在我的 init
方法中初始化一个变量,但它似乎在调用链到达 awakeFromNib
时被释放。我已经阅读了几个主题,而且太多的主题似乎都有同样的困惑 - 应该非常简单明了的东西...... :(.
- (id)init {
self = [super initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];
if (self) {
self.customObject = [CustomObject currentInstance]; //OK
}
}
- (void)awakeFromNib {
[self.customObject someMethod]; //here self.customObject is nil?
//self.customObject = [CustomObject currentInstance]; // Why should I do this here?
}
我的 .m
文件中的声明没什么特别的。我不想在不了解 背后的原因 的情况下在 awakeFromNib
中分配 属性。
@property (strong) CustomObject *customObject;
CustomObject实例化.m文件
static CustomObject customObject;
@implementation CustomObject {
+ (instancetype)initMockCustomObject {
customObject = (CustomObject*)[OCMockObject mockForClass:[CustomObject class]];
}
+ (instancetype)currentInstance {
if ( customObject == nil) { [NSException raise...]; }
return customObject;
}
}
initMockCustomObject
已在 AppDelegate 中调用。
编辑:在 init
中添加了对 initWithNibName
方法的实际超级调用。
Edit2:添加了单例实例
感谢您的意见。我创建了一个绝对最小的沙盒项目,我发现我的一个父 NIB 中有一个对象,它与 MyViewController 的类型相同,导致了这个问题。关闭这个问题,因为它太特定于应用程序。 init中初始化变量的基本问题就OK了