2016-01-20 41 views
0

出於某種原因,我遇到了一個問題,在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仍然發送下弧 –

回答

0

的問題是在這裏:

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

它需要weakSelf ...

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

不要問我爲什麼,我的大腦爆炸。