简体   繁体   English

iOS / Objective-C:排除空值

[英]IOS/Objective-C: Exclude empty values

I thought I had seen every possible flavor of values for properties that have not been set in an object, but evidently I have not. 我以为我看到了未在对象中设置的属性的所有可能值,但显然我没有。

Basically, I want to exclude cases where a value has not been set for a string property of an NSManagedObject . 基本上,我想排除未为NSManagedObject的字符串属性设置值的情况。 In fact, I want to exclude every case except where there is a valid string of 4 characters or more. 实际上,我想排除所有情况, 除非存在有效的4个字符或更多字符的字符串。

I was using the following code: 我正在使用以下代码:

if (![contact.pic isKindOfClass:[NSNull class]]&&contact.pic.length>4) {
           //I have a valid string
        }
        else {
            //I don't have valid string
        }

However, it is not excluding some values (most likely where a value was never set) where it logs the values to console as follows: 但是,它不会排除某些值(很可能从未设置过值),它会将这些值记录到控制台,如下所示:

NSLog(@"contact.pic is: %@",contact.pic); //logs (null)

Can anyone suggest bullet proof code to exclude all but valid strings greater than four characters? 任何人都可以建议使用防弹代码,以排除所有有效字符串(大于四个字符)吗?

Thanks in advance for any suggestions 在此先感谢您的任何建议

It looks like you are not catching the case where the value is nil, have you tried including a catch for this too 看来您没有抓住值为零的情况,您是否也尝试过为此抓住

if (contact.pic && ![contact.pic isKindOfClass:[NSNull class]] && contact.pic.length >= 4) {
    //I have a valid string
}
else {
    //I don't have valid string
}

Note that I have also made your inequality >= rather than > since your question suggests that 4 is a valid value. 请注意,由于您的问题表明4是有效值,因此我也使您的不等式>=而不是>

I usually use following three macros in every project for NSString validations as required 我通常根据需要在每个项目中使用以下三个宏进行NSString验证

#define IfNULL(original, replacement) IsNULL(original) ? replacement : original

#define IsNULL(original) original == (id)[NSNull null] || original == nil

#define IsEmpty(value) (value == (value == nil) || (id)[NSNull null] || ([value isKindOfClass:[NSString class]] && ([value isEqualToString:@""] || [value isEqualToString:@"<null>"] || [value isEqualToString:@"(null)"] || [value isEqualToString:@" "]))) ? YES : NO

Usage 用法

if(!isEmpty(contact.pic)){
    //Do your stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM