nil:指向oc中對象的空指針spa
Nil:指向oc中類的空指針指針
NULL:指向其餘類型的空指針,如一個c類型的內存指針code
NSNull:在集合對象中,表示空值的對象orm
nil和NULL從字面意思來理解比較簡單,nil是一個對象,而NULL是一個值,個人理解爲nil是將對象設置爲空,而NULL是將基本類型設置爲空的對象
這些概念很容易混淆,在一些場合下他們具備一樣的用法。首先解釋一下「空指針」意思,空指針是指該指針未指向一塊有意義的內存區。如int *p; int *p = NULL;three
NSObject *obj1 = [[NSObject alloc] init]; NSObject *obj2 = [NSNull null]; NSObject *obj3 = [NSObject new]; NSObject *obj4; NSArray *arr1 = [NSArray arrayWithObjects:obj1, obj2, obj3, obj4, nil]; NSLog(@"arr1 count: %ld", [arr1 count]); //count: 3 由於obj=nil,在加入obj4時就結束添加對象 NSObject *obj1; NSObject *obj2 = [[NSObject alloc] init]; NSObject *obj3 = [NSNull null]; NSObject *obj4 = [NSObject new]; NSArray *arr2 = [NSArray arrayWithObjects:obj1, obj2, obj3, obj4, nil]; NSLog(@"arr2 count: %ld", [arr2 count]); //count: 0,由於obj1=nil,因此後面的對象沒有添加進去 [NSNull null]一般做爲佔位符做用,以下: NSObject *obj1 = [NSNull null]; NSArray *arr1 = [NSArray arrayWithObjects:@"One", @"TWO", obj1,@"three",nil]; for (NSString *str in arr1) { NSLog(@"array object: %@", str); } //result:One、Two、、three NSObject *obj1 = [NSNull null]; NSArray *arr1 = [NSArray arrayWithObjects:@"One", @"TWO", obj1,@"three",nil]; for (NSString *str in arr1) { if (str != [NSNull null]){ NSLog(@"array object: %@", str); } }//result:One、Two、three