Explanation of nil, Nil, NULL, and NSNull in iOS
This article mainly introduces the detailed information about nil, Nil, NULL, and NSNull in iOS. For more information, see
Several null symbols in ObjC often almost killed me. These basic things need to be clarified to improve the basic quality of code farmers.
Nil
Nil is the literal null value of the ObjC object, corresponding to the id type object, or the ObjC object declared by @ interface.
For example:
?
1 2 3 4 |
NSString * someString = nil; NSURL * someURL = nil; Id someObject = nil; If (anotherObject = nil) // do something |
Definition:
?
1 2 3 4 5 6 7 8 9 10 11 12 |
// Objc. h # Ifndef nil # If _ has_feature (cxx_nullptr) # Define nil nullptr # Else # Define nil _ DARWIN_NULL # Endif # Endif // _ DARWIN_NULL in _ types. h # Define _ DARWIN_NULL (void *) 0) |
Nil
Nil is a written null value of the ObjC Class type, which corresponds to a Class object.
For example:
Class someClass = Nil;
Class anotherClass = [NSString class];
The definition Definition is similar to that of nil, with the same value:
?
1 2 3 4 5 6 7 8 |
// Objc. h # Ifndef Nil # If _ has_feature (cxx_nullptr) # Define Nil nullptr # Else # Define Nil _ DARWIN_NULL # Endif # Endif |
NULL
NULL is a NULL value of any C pointer.
For example:
?
1 2 3 |
Int * pointerToInt = NULL; Char * pointerToChar = NULL; Struct TreeNode * rootNode = NULL; |
Definition:
?
1 2 |
// In stddef. h # Define NULL (void *) 0) |
NSNull
NSNull is a class that represents null values and is an ObjC object. In fact, it only has one Singleton method: + [NSNull null], which is generally used to indicate objects with null values in the set.
Example:
// Nil cannot be stored in the Foundation set because nil is used to end the set.
NSArray * array = [NSArray arrayWithObjects: @ "one", @ "two", nil];
// Incorrect use
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
[Dict setObject: nil forKey: @ "someKey"];
// Correct use
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
[Dict setObject: [NSNull null] forKey: @ "someKey"];
Definition:
?
1 2 3 4 5 6 7 |
/* NSNull. h Copyright (c) 1994-2012, Apple Inc. All rights reserved. */ # Import <Foundation/NSObject. h> @ Interface NSNull: NSObject <NSCopying, NSSecureCoding> + (NSNull *) null; @ End |
Summary
Although the values of nil, Nil, and NULL are the same, it is important to understand the written meaning between them, so that the code is clearer and more readable.
The above is all the content of this article. I hope you will like it.