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

后端 未结 20 1751
梦毁少年i
梦毁少年i 2020-11-27 09:26

I was using this in my iPhone app

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

but it throws some exception, and the console shows that the ti

相关标签:
20条回答
  • 2020-11-27 09:51
    @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.

    0 讨论(0)
  • 2020-11-27 09:57

    Refer to the following related articles on this site:

    • Is if (variable) the same as if (variable != nil) in Objective-C h

    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

    0 讨论(0)
  • 2020-11-27 09:57
    if(textfield.text.length == 0){
       //do your desired work
    }
    
    0 讨论(0)
  • 2020-11-27 09:58

    If that kind of thing does not already exist, you can make an NSString category:

    @interface NSString (TrucBiduleChoseAdditions)
    
    - (BOOL)isEmpty;
    
    @end
    
    @implementation NSString (TrucBiduleChoseAdditions)
    
    - (BOOL)isEmpty {
        return self == nil || [@"" isEqualToString:self];
    }
    
    @end
    
    0 讨论(0)
  • 2020-11-27 10:02

    For string:

    + (BOOL) checkStringIsNotEmpty:(NSString*)string {
    if (string == nil || string.length == 0) return NO;
    return YES;
    

    }

    Refer the picture below:

    0 讨论(0)
  • 2020-11-27 10:03

    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

    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 讨论(0)
提交回复
热议问题