1. 程式人生 > >(iPhone/iPad)NSString中讓人費解的nil和NSNull,待解惑

(iPhone/iPad)NSString中讓人費解的nil和NSNull,待解惑

今天在用到NSString類的時候遇到一個問題,挺費解的,問題是這樣的:我從伺服器上獲取某字串資料,考慮到有些物件不含這個字串變數,我在使用時先判斷該字串是否為空,例如:

假設,這個字串名叫str,

先判斷if(str!=nil){

//do something

double data=[str doubleValue];

}

但是,當資料為空時依舊報錯,錯誤內容如下:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:'-[NSNull doubleValue]: unrecognized selector sent to instance 0x2b4ccd8'
***Firstthrow call stack:(0x2ab60520x28d6d0a0x2ab7ced0x2a1cf000x2a1cce20x14ff1c0x14e93c0x10cdf10x105c880x133b400x1359350x15325480x15347220x13e47c70x13e42c10xd1e3d660x13e728c0x13e72b80x13e79ab0x13ec2880xd1e3ece0xb52620xcf55f0xb72c30x141d64e0x141cc1c0x144356d0x142dd470x14444410x14444f90x163bc680x13fb4a10x13fc12b0x163b4c70x14244270x142458c0xd1fe280
0x14245cc0xecdaf0xf14e20xecb9d0xd5d0e0x135e880x1070980x12d8700x2ab7ec90x135a5c20x135a55a0x13ffb760x140003f0x13ff2fe0x137fa300x137fc560x13663840x1359aa90x28b9fa90x2a8a1c50x29ef0220x29ed90a0x29ecdb40x29ecccb0x28b88790x28b893e0x1357a9b0x186560x2be50x1) terminate called throwing an exception
顯示[NSNull doubleValue]...也就是說,我之前在if中判斷(str!=nil)並不足以判斷NSNull...這是為什麼?nil和NSNull又有什麼區別???

當我檢視蘋果官方文件時,有這麼一個程式碼:

id aValue = [arrayWithNull objectAtIndex:0];
if (aValue == nil) {
    NSLog(@"equals nil");
} else if (aValue == [NSNull null]) {
    NSLog(@"equals NSNull instance");
    if ([aValue isEqual:nil]) {
        NSLog(@"isEqual:nil");
    }
}
// output: "equals NSNull instance"

雖然最後我的問題解決了,我在if判斷中用
if(![tmpNewsModel.latitude isEqual:[NSNull null]]){
     //do something
}


問題是解決了,但是還不太理解nil和NSNull的區別?今天時間不太夠,先記下這個問題,有時間想想這個區別!