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
+(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 :)
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
#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");
NSString *str;
if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""] || str==nil)
{
}