LoginSignup
0
0

More than 5 years have passed since last update.

nil 的用法

Last updated at Posted at 2015-05-12

在 Objective-C 裡,
不像 C 的一些 scaler variables ,不給初始值時,會是 stack 中前一個變數所殘留的值,
一個物件的 pointer 可以不用給任何初始值,他的初始值就是 nil

對 nil object 傳訊息則不會有任何問題發生,也不會 error 或 crash 。

回傳值

當對 nil object 傳送訊息預期會有回傳值時,則會根據不同的型態、回傳對應的值:

Return Type Returns
物件 nil
數字 (numeric) 0
BOOL NO
資料結構,如 CGRect 所有內含成員變數的值皆是 0

檢查空值 nil

判斷是空值

當要檢查一個物件確定為空值時

if (anObject == nil) {
}

可以這樣直接把條件式放入變數就好:

if (anObject) {
}

判斷不是空值

反之,當要檢查一個物件 不是 空值時

if (anObject != nil) {
}

這樣一樣太囉唆了點,一樣可以改成這樣:

if (!anObject) {
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0