self always returns nil inside viewController's methods

self always returns nil inside viewController's methods

出于某种原因,我遇到了一个问题,在 viewController 的代码中(在调用 viewDidLoad 方法后 运行),self 总是 returns零。 (运行 在 iPad Air 上使用 iOS 9.2.1,应用以 9.2 作为目标构建)。

在初始化代码中我们有一个运行-of-the-mill 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 class 和 .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 不是 nil,ipAddressLabel 也不是 nil。但是,当 运行 时间到达 self.ipAddressLabel.text 时,它会通过 initWithNibName,并且 returns nil 为自己!然后 ipAddressLabel 被设置为 nil,然后它在视图中变为空白。

此时myVC已经成功加载并显示在屏幕上。所以我不明白为什么在这个方法中 self 为自己返回 nil ......这很奇怪。

如果我删除了对 initWithNibName 方法的覆盖,那么一切都会完美运行。如果我在设置 self=[super...] 之前检查 initWithNib 名称开头的 if (self != nil),则视图在屏幕上绘制的位置太低了大约 1" 并被截断。

只是想了解为什么会这样。谢谢。

问题出在这里:

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

需要弱自...

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

别问我为什么,脑子炸了