Objective-C:NULL,nil和@“"之间有什么区别?
正如标题所说,NULL
,nil
和@""
有什么区别?
As the title says, what's the difference between NULL
, nil
and @""
?
例如,如果我要检查字典中的字符串是否为空.
For example, if I want to check a string in a dictionary is empty.
我应该使用哪种情况?
if ([dictionary objectForKey:@"aString"] == nil)
或
if [[dictionary objectForKey:@"aString"] isEqualToString:@""]
或
if ([dictionary objectForKey:@"aString"] == NULL)
哪个是对的?
nil
是object-c对象的NULL模拟.实际上,它们是相同的:
nil
is NULL's analog for objective-c objects. Actually they're the same:
//MacTypes.h
#define nil NULL
所以
if ([dictionary valueForKey:@"aString"]==nil)
if ([dictionary valueForKey:@"aString"]==NULL)
都检查字典中是否存在特定的键,尽管第一行在检查Objective-C类型时更正确.
both check if the specific key is present in a dictionary, although 1st line is more correct as it checks objective-c types.
关于:
if ([[dictionary valueForKey:@"aString"] isEqualToString:@""])
此行检查字典中是否存在带有"aString"键的条目,并将该条目与空字符串进行比较.结果将是以下之一:
This line checks if there's an entry in dictionary with "aString" key and compares that entry with empty string. The result will be one of the following:
-
如果您的密钥中没有这样的条目,则
- 为假
- 如果键的条目为空且该条目为空字符串,则为true 如果您的密钥对象存在并且不响应
- 可能会崩溃
-isEqualToString:
消息,- is false if there's no such entry for your key
- is true if there's entry for your key and that entry is empty string
- may crash if object for your key exists and does not respond to
-isEqualToString:
message
因此,根据您的需要,您必须使用第一行,或者如果您需要同时检查条目是否存在以及它是否为空字符串,那么您需要两个条件:
So depending on your needs you must use 1st line, or if you need to combine both checking if entry exists and it is not an empty string then you need 2 conditions:
if ([dictionary valueForKey:@"aString"]==nil ||
[[dictionary valueForKey:@"aString"] isEqualToString:@""])