How to check the NULL value in NSString in iOS?

前端 未结 10 1581
盖世英雄少女心
盖世英雄少女心 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: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
    

提交回复
热议问题