How to validate the empty string in Objective C?
I want to validate the string value after getting in the below parser delegate method
I have tried like [string lengt开发者_如何学Pythonh]>0 ,(string !=NULL) in if condition still blank string is printed in the NSlog.So what is the efficient method to validate the sting.I have used the below code.
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if ([elemName isEqualToString:@"productName"]) {
if (!prodStringValue) {
prodStringValue = [[NSMutableString alloc] initWithCapacity:50];
}
[prodStringValue appendString:string];
if(prodStringValue && [prodStringValue length]>0 && (prodStringValue !=NULL))
{
prodNameStr = prodStringValue;
NSLog(@"productName:%@",prodNameStr);
}
if(string && [string length]>0 && (string !=NULL))
{
prodNameStr = string;
NSLog(@"productName:%@",string);
}
}
}
Do you have whitespaces in this "empty" string? Be sure to delete them using
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
You can check if [string length] == 0
. This will check if it's a valid but empty string (@""
) as well as if its nil, since calling length
on nil will also return 0.
You may use the following code instead of all three checks, I suppose.
[prodStringValue isEqualToString:@""];
And, BTW
if (prodStringValue)
equals to
if (prodStringValue != nil) // nil = NULL in objc
if (str == Nil)
Try This. Works For Me.
you can try this below few lines of code
NSString *trimedstr = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if(trimedstr != [NSNull null]&& ![trimedstr isEqualToString:@""])
{
if([trimedstr length]>0)
{
NSLog(@"%@", trimedstr);
}
}
In case of string is NULL and you check it's length then it will crash. so you may try.
string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if(string != [NSNull null])
{
if([string length]>0)
{
NSLog(@"%@",string);
}
}
[str isEqualToString:@""]
It is best way for nil string.
精彩评论