自我总是返回nil里面viewController的方法

问题描述:

出于某种原因,我遇到了一个问题,在viewController的代码(它在调用viewDidLoad方法后运行良好)内,self总是返回nil。 (运行iOS 9.2.1的iPad Air,以9.2为目标的应用程序)。自我总是返回nil里面viewController的方法

在初始化代码我们运行的设施,工厂一initter:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    }; 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { } 
    return self; 
} 

的的viewController被实例化这样的:

myVC * myVC = [[myVC alloc] initWithNibName:nil bundle:nil]; 

的myVC类的.xib的名字文件是一样的。

有一个名为属性:

@property (weak, nonatomic) IBOutlet UILabel *ipAddressLabel; 

在里面myVC的方法,我的方法是这样的:

- (void) networkPropertiesDidChange:(NSDictionary *)properties { 
    void (^completionBlock)(UIAlertAction *) = ^(UIAlertAction *action) { 
     [self.serialNumberField setEnabled:false]; 
    }; 
    if([properties[@"result" isEqualToString @"error"]) { 
     [Utility showBasicAlertControllerWithText:@"Device not registered." completionBlock:completionBlock sender:self]; 
     return; 
    } 
    else if ([properties[@"result"] isEqualToString @"ipChange"]) { 
     NSString *newAddy = [[NSString alloc] initWithString:properties[@"ipAddress"]]; 
     self.ipAddressLabel.text = newAddy; 
     return; 
    } 
    else return; 
} 

但是地址标签只是一片空白。

当我执行代码时,在我初始化newAddy的那一行上,self不是零,ipAddressLabel也不是零。但是,当运行时命中self.ipAddressLabel.text时,它会通过initWithNibName,并自行返回!然后ipAddressLabel被设置为零,然后在视图上变为空白。

此时myVC已经成功加载并在屏幕上。所以我无法理解为什么自己在这种方法中自我回归零...这很奇怪。

如果我删除了我对initWithNibName方法的覆盖,那么所有东西都能正常工作。如果我在设置self = [super ...]之前检查initWithNib名称的开始处是否(se​​lf!= nil),则视图在屏幕上画出约1“太低并被切断。 。明白为什么这发生由于

+0

只是一些想法:1)添加一个NSLog的dealloc方法,看看是否被调用(并出于某种原因,这个对象不会被保留) - 2)添加自己的客户setter为您的ipAddressLabel,随着价值的东西(看看它是否没有)。在您的方法中添加断言(或NSAsserts)以测试ipAddressLabel是否为零。 –

+0

无法添加dealloc,我正在使用ARC。我已经尝试添加自定义setter,但无法在无对象上调用方法。我添加断言和ipAddressLabel不是零,直到我调用'self.ipAddressLabel.text = newAddy;'... – CommaToast

+0

Dealloc仍然发送下弧 –

的问题是在这里:

void (^completionBlock)(UIAlertAction *) = ^(UIAlertAction *action) { 
    [self.serialNumberField setEnabled:false]; 
}; 

它需要weakSelf ...

__weak typeof(self) weakSelf = self; 
    void (^completionBlock)(UIAlertAction *) = ^(UIAlertAction *action) { 
     [weakSelf.paxSerialNumberField setEnabled:false]; 
    }; 

不要问我为什么,我的大脑爆炸。