Can I simply use
if(myString == nil)
For some reason a string that I know is null, is failing this statement.
Can I simply use
if(myString == nil)
For some reason a string that I know is null, is failing this statement.
Is it possible that your string is not in fact nil
, and is instead just an empty string? You could try testing whether [myString length] == 0
.
You can find more on objective C string here.
+ (BOOL ) stringIsEmpty:(NSString *) aString {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
} else {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
+ (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
}
if (cleanWhileSpace) {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
you may check your getting string using this
if(myString==(id) [NSNull null] || [myString length]==0 || [myString isEqualToString:@""])
{
//String is null or bad response
}
It seems that my string in the debugger was reporting as (null) but that was due to how it was being assigned, I fixed it and now it is reporting as nil. This fixed my issue.
Thanks!
Notice length = 0 doesn't necessary mean it's nil
NSString *test1 = @"";
NSString *test2 = nil;
They are not the same. Although both the length are 0.
You can implicitly check for nil
(allocated, but not initialized) with this:
if (!myString) {
//do something
}
If myString
was assigned from a dictionary or array, you may also wish to check for NSNULL
like this:
if ([myString isEqual:[NSNull null]]) {
//do something
}
Finally (as Sophie Alpert mentioned), you can check for empty strings (an empty value):
if ([myString length] == 0) {
//do something
}
Often, you may want to consolidate the expressions:
if (!myString || [myString length] == 0) {
//do something
}
I encountered this problem today. Despite assigning a string to be nil: NSString *str = nil;
, the test if (str == nil)
returned FALSE
! Changing the test to if (!str)
worked, however.
Check NSAttributedString is empty:
let isEmpty = atrributedString.string.isEmpty