nil用來給對象賦值(Objective-C中的任何對象都屬於id類型),NULL則給任何指針賦值,NULL和nil不能互換,nil用於類指針賦值(在Objective-C中類是一個對象,是類的meta-class的實例), 而NSNull則用於集合操作,雖然它們表示的都是空值,但使用的場合完全不同。
示例如下:
- id object = nil;
- // 判斷對象不為空
- if (object) {
- }
- // 判斷對象為空
- if (object == nil) {
- }
- // 數組初始化,空值結束
- NSArray *array = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];
- // 判斷數組元素是否為空
- NSString *element = [array objectAtIndex:2];
- if ((NSNull *)element == [NSNull null]) {
- }
- // 判斷字典對象的元素是否為空
- NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
- @"iPhone", @"First", @"iPad", @"Second", nil];
- NSString *value = [dictionary objectForKey:@"First"];
- if ((NSNull *)value == [NSNull null]) {
- }