How to check the NULL value in NSString in iOS?

前端 未结 10 1527
盖世英雄少女心
盖世英雄少女心 2021-01-02 15:17

I have an NSString and I want to check if it has a NULL value. If it does, then the if condition should execute. Else it should execut

相关标签:
10条回答
  • 2021-01-02 16:06
    +(BOOL)isEmpty:(NSString *)str{
        if (str == nil || str == (id)[NSNull null] || [[NSString stringWithFormat:@"%@",str] length] == 0 || [[[NSString stringWithFormat:@"%@",str] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
            return YES;
        }
        return NO;
    }
    

    Just pass your string in Method :)

    0 讨论(0)
  • 2021-01-02 16:08

    Use the following code:

    -(void)viewDidLoad {
      [super viewDidLoad];
      //Example - 1
        NSString *myString;
        if([[self checkForNull:myString] isEqualToString:@""]){
    
            NSLog(@"myString is Null or Nil");
    
       }
       else{
    
         NSLog(@"myString contains %@",myString);
    
       }
    
     //Example - 2
       NSString *sampleString = @"iOS Programming";
        if([[self checkForNull:sampleString] isEqualToString:@""]){
    
            NSLog(@"sampleString is Null or Nil");
    
       }
       else{
    
         NSLog(@"sampleString contains %@",sampleString);
    
       }
    
    
    }
    
    -(id)checkForNull:(id)value{
        if ([value isEqual:[NSNull null]]) {
    
                return @"";
       }
    
        else if (value == nil)
    
                return @"";
        return value;
    
    }
    

    In Example -1, myString contains nothing. So the output is:

             myString is Null or Nil
    

    In Example -2, sampleString contains some value. So the output is:

        sampleString contains iOS Programming
    
    0 讨论(0)
  • 2021-01-02 16:09
    #define SAFESTRING(str) ISVALIDSTRING(str) ? str : @""
    #define ISVALIDSTRING(str) (str != nil && [str isKindOfClass:[NSNull class]] == NO)
    #define VALIDSTRING_PREDICATE [NSPredicate predicateWithBlock:^(id evaluatedObject, NSDictionary *bindings) {return (BOOL)ISVALIDSTRING(evaluatedObject);}]
    

    SAFESTRING("PASS_OBJECT_HERE");

    0 讨论(0)
  • 2021-01-02 16:09
      NSString *str;
    
      if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]          isEqualToString:@""] || str==nil) 
      {
    
      }
    
    0 讨论(0)
提交回复
热议问题