Objective-C:NULL,nil和@“"之间有什么区别? [英] Objective-C: What's the difference between NULL, nil and @""?

查看:116
本文介绍了Objective-C:NULL,nil和@“"之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,NULLnil@""有什么区别?

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:@""])

这篇关于Objective-C:NULL,nil和@“"之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆