Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 length]>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);
        }

    }
}

2 Answers

Do you have whitespaces in this "empty" string? Be sure to delete them using

NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceAndNewlineCharacterSet]];
like image 167
tilo Avatar answered Jul 09 '26 04:07

tilo


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.

like image 41
Odys Avatar answered Jul 09 '26 04:07

Odys