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
@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
.
Refer to the following related articles on this site:
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
if(textfield.text.length == 0){
//do your desired work
}
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
For string:
+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;
}
Refer the picture below:
Whats with all these "works for me answers" ? We're all coding in the same language and the rules are
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.