ios 在 Objective-C 中检查空字符串的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/968792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:59:48  来源:igfitidea点击:

What is the right way to check for a null string in Objective-C?

iosobjective-ccocoa-touch

提问by Teo Choong Ping

I was using this in my iPhone app

我在我的 iPhone 应用程序中使用了这个

if (title == nil) {
    // do something
}

but it throws some exception, and the console shows that the title is "(null)".

但它引发了一些异常,并且控制台显示标题为“(空)”。

So I'm using this now:

所以我现在使用这个:

if (title == nil || [title isKindOfClass:[NSNull class]]) {
    //do something
}

What is the difference, and what is the best way to determine whether a string is null?

有什么区别,确定字符串是否为空的最佳方法是什么?

回答by Peter N Lewis

As others have pointed out, there are many kinds of "null" under Cocoa/Objective C. But one further thing to note is that [title isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null.

正如其他人所指出的,在 Cocoa/Objective C 下有很多种“null”。但要注意的另一件事是 [title isKindOfClass:[NSNull class]] 是毫无意义的复杂,因为 [NSNull null] 被记录为一个单例,所以你可以只检查指针相等。请参阅Cocoa 主题:使用 Null

So a good test might be:

所以一个好的测试可能是:

if (title == (id)[NSNull null] || title.length == 0 ) title = @"Something";

Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.

请注意,即使 title 为 nil,title.length 也将返回 0/nil/false,即在这种情况下为 0,因此您不必对它进行特殊处理,请注意如何使用这一事实。这是Objective C的新手很难习惯的东西,特别是来自其他语言的消息/方法调用nil崩溃。

回答by Bluephlame

it is just as simple as

就这么简单

if([object length] >0)
{
  // do something
}

remember that in objective C if object is null it returns 0 as the value.

请记住,在目标 C 中,如果 object 为 null,则它返回 0 作为值。

This will get you both a null string and a 0 length string.

这将为您提供一个空字符串和一个长度为 0 的字符串。

回答by TimM

Refer to the following related articles on this site:

参考本站以下相关文章:

I think your error is related to something else as you shouldn't need to do the extra checking.

我认为您的错误与其他事情有关,因为您不需要进行额外的检查。

Also see this related question: Proper checking of nil sqlite text column

另请参阅此相关问题:正确检查 nil sqlite 文本列

回答by Guardius

I have found that in order to really do it right you end up having to do something similar to

我发现为了真正做到正确,你最终不得不做类似的事情

if ( ( ![myString isEqual:[NSNull null]] ) && ( [myString length] != 0 ) ) {
}

Otherwise you get weird situations where control will still bypass your check. I haven't come across one that makes it past the isEqualand length checks.

否则你会遇到奇怪的情况,控制仍然会绕过你的检查。我还没有遇到过一个通过isEqual长度检查的方法。

回答by nenchev

Whats with all these "works for me answers" ? We're all coding in the same language and the rules are

所有这些“对我有用的答案”是什么?我们都用同一种语言编码,规则是

  1. Ensure the reference isn't nil
  2. Check and make sure the length of the string isn't 0
  1. 确保引用不为零
  2. 检查并确保字符串的长度不为 0

That is what will work for all. If a given solution only "works for you", its only because your application flow won't allow for a scenario where the reference may be null or the string length to be 0. The proper way to do this is the method that will handle what you want in all cases.

这对所有人都有效。如果给定的解决方案仅“适合您”,那只是因为您的应用程序流不允许引用可能为空或字符串长度为 0 的情况。正确的方法是处理在所有情况下你想要什么。

回答by diederikh

If you want to test against all nil/empty objects (like empty strings or empty arrays/sets) you can use the following:

如果要针对所有 nil/空对象(如空字符串或空数组/集)进行测试,可以使用以下命令:

static inline BOOL IsEmpty(id object) {
    return object == nil
        || ([object respondsToSelector:@selector(length)]
        && [(NSData *) object length] == 0)
        || ([object respondsToSelector:@selector(count)]
        && [(NSArray *) object count] == 0);
}

回答by gnasher729

There are two situations:

有两种情况:

It is possible that an object is [NSNull null], or it is impossible.
Your application usually shouldn't use [NSNull null];you only use it if you want to put a "null" object into an array, or use it as a dictionary value. And then you should know which arrays or dictionaries might contain null values, and which might not.
If you think that an array never contains [NSNull null]values, then don't check for it. If there is an [NSNull null], you might get an exception but that is fine: Objective-C exceptions indicate programming errors. And you have a programming error that needs fixing by changing some code.

一个对象可能是[NSNull null],或者是不可能的。
您的应用程序通常不应该[NSNull null];只在您想将“”对象放入数组中时才使用它,或者将其用作字典值。然后您应该知道哪些数组或字典可能包含空值,哪些可能不包含。
如果您认为数组从不包含[NSNull null]值,请不要检查它。如果有[NSNull null],您可能会得到一个异常,但这很好:Objective-C 异常表示编程错误。并且您有一个需要通过更改一些代码来修复的编程错误。

If an object couldbe [NSNull null], then you check for this quite simply by testing
(object == [NSNull null]). Calling isEqualor checking the class of the object is nonsense. There is only one [NSNull null]object, and the plain old C operator checks for it just fine in the most straightforward and most efficient way.

如果一个对象可能[NSNull null],那么您可以通过测试非常简单地检查这一点
(object == [NSNull null])。调用isEqual或检查对象的类是无稽之谈。只有一个[NSNull null]对象,而普通的老式 C 运算符以最直接和最有效的方式检查它就好了。

If you check an NSStringobject that cannot be [NSNull null](because you know it cannot be [NSNull null]or because you just checked that it is different from [NSNull null], then you need to ask yourself how you want to treat an empty string, that is one with length 0. If you treat it is a nullstring like nil, then test (object.length == 0). object.length will return 0 if object == nil, so this test covers nil objects and strings with length 0. If you treat a string of length 0 different from a nil string, just check if object == nil.

如果您检查一个NSString不能为的对象[NSNull null](因为您知道它不能为,[NSNull null]或者因为您刚刚检查了它与 不同[NSNull null],那么您需要问自己您想如何处理长度为 0 的空字符串。如果您把它null当作一个字符串nil,然后 test (object.length == 0). object.length 将返回 0 if object == nil,所以这个测试覆盖 nil 对象和长度为 0 的字符串。如果你处理一个长度为 0 的字符串与一个 nil 字符串不同,只需检查 if object == nil

Finally, if you want to add a string to an array or a dictionary, and the string could be nil, you have the choice of not adding it, replacing it with @"", or replacing it with [NSNull null]. Replacing it with @""means you lose the ability to distinguish between "no string" and "string of length 0". Replacing it with [NSNull null]means you have to write code when you access the array or dictionary that checks for [NSNull null]objects.

最后,如果您想将一个字符串添加到数组或字典中,并且该字符串可能为 nil,您可以选择不添加、替换为@""或替换为[NSNull null]。将其替换为@""意味着您将无法区分“无字符串”和“长度为 0 的字符串”。替换它[NSNull null]意味着您必须在访问检查[NSNull null]对象的数组或字典时编写代码。

回答by Gami Nilesh

You just check for nil

你只需检查 nil

if(data[@"Bonds"]==nil){
  NSLog(@"it is nil");
}

or

或者

if ([data[@"Bonds"] isKindOfClass:[NSNull class]]) {
    NSLog(@"it is null");
}

回答by mgyky

MACRO Solution (2020)

宏解决方案 (2020)

Here is the macro that I use for safe string instead of getting "(null)" string on a UILabelfor example:

这是我用于安全字符串的宏,而不是在UILabel上获取 " (null)" 字符串,例如:

#define SafeString(STRING) ([STRING length] == 0 ? @"" : STRING)

let say you have an member class and name property, and name is nil:

假设您有一个成员类和 name 属性,并且 name 为零:

NSLog(@"%@", member.name); // prints (null) on UILabel

with macro:

带宏:

NSLog(@"%@", SafeString(member.name)); // prints empty string on UILabel

nice and clean

漂亮干净

Extension Solution (2020)

扩展解决方案 (2020)

If you prefer checking nil Null and empty string in your project you can use my extension line below:

如果你更喜欢在你的项目中检查 nil Null 和空字符串,你可以使用我下面的扩展行:

NSString+Extension.h

NSString+扩展.h

///
/// Checks if giving String is an empty string or a nil object or a Null.
/// @param string string value to check.
///
+ (BOOL)isNullOrEmpty:(NSString*)string;

NSString+Extension.m

NSString+扩展名.m

+ (BOOL)isNullOrEmpty:(NSString*)string {
    if (string) { // is not Nil
        NSRange range = [string rangeOfString:string];
        BOOL isEmpty = (range.length <= 0 || [string isEqualToString:@" "]);
        BOOL isNull = string == (id)[NSNull null];

        return (isNull || isEmpty);
    }

    return YES;
}

Example Usage

示例用法

if (![NSString isNullOrEmpty:someTitle]) {
    // You can safely use on a Label or even add in an Array for example. Remember: Arrays don't like the nil values!
}

回答by Hemang

@interface NSString (StringFunctions)
- (BOOL) hasCharacters;
@end

@implementation NSString (StringFunctions)
- (BOOL) hasCharacters {
    if(self == (id)[NSNull null]) {
        return NO;
    }else {
        if([self length] == 0) {
            return NO;
        }
    }
    return YES;
}
@end

NSString *strOne = nil;
if([strOne hasCharacters]) {
    NSLog(@"%@",strOne);
}else {
    NSLog(@"String is Empty");
}

This would work with the following cases, NSString *strOne = @""OR NSString *strOne = @"StackOverflow"OR NSString *strOne = [NSNull null]OR NSString *strOne.

这适用于以下情况NSString *strOne = @""OR NSString *strOne = @"StackOverflow"OR NSString *strOne = [NSNull null]OR NSString *strOne