iOS中nil 、NULL、 Nil 、NSNull的詳解(一)

來源:互聯網
上載者:User

標籤:nil null nil nsnull   ios   指標   

1.nil
  >Defines the id of a null instance.
  定義一個執行個體為空白, 指向oc中對象的null 指標.
  >範例程式碼:
   NSString *someString = nil;
   NSURL *someURL = nil;
   id someObject = nil;
   if (anotherObject == nil) // do something

  >當對某個對象release 的同時最好把他們賦值為nil,這樣可以確保安全性,如果不賦值nil,可能導致程式崩潰.
      NSArray * array = [NSArray arrayWithObjects:@"test",@"test1" ,nil];
      [array release];
      
      if (array)
      {
      //僅僅對數組release,並沒有賦值為nil,在程式某個地方如果繼續對數組操作,程式直接崩潰
          NSString * string = [array objectAtIndex:0];
          NSLog(@"%@",string);
      }


  2.NULL
  >These macros define null values for classes and instances.
  NULL可以用在C語言的各種指標上,
  #define __DARWIN_NULL #define__DARWIN_NULLConstants

  >範例程式碼:
  int *pointerToInt = NULL;
  char *pointerToChar = NULL;
  struct TreeNode *rootNode = NULL;

  >在Objective-C裡,nil對象被設計來跟NULLnull 指標關聯的。他們的區別就是nil是一個對象,而NULL只是一個值。而且我們對於nil調用方法,不會產生crash或者拋出異常。

  3.Nil
  >Defines the id of a null class.
  定義一個空的類
  Available in Mac OS X v10.0 through Mac OS X v10.4.
  Declared in NSObjCRuntime.h.
  Declared Inobjc.h
  >範例程式碼:
  Class someClass = Nil;
  Class anotherClass = [NSString class];


  4.NSNull
  >The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).
  NSNull類定義了一個單例對象用於表示集合對象的空值

  >集合對象無法包含nil作為其具體值,如NSArray、NSSet和NSDictionary。相應地,nil值用一個特定的對象NSNull來表示。NSNull提供了一個單一執行個體用於表示對象屬性中的的nil值。預設的實現方法中,dictionaryWithValuesForKeys:和setValuesForKeysWithDictionary:自動地將NSNull和nil相互轉換,因此您的對象不需要進行NSNull的測試操作。

iOS中nil 、NULL、 Nil 、NSNull的詳解(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.