iosobjective-ckissxml

How to find out if DDXMLElement has a value?


I have a XML WebService (and no chance to change this) elements can be empty but I see no obvious way to do this using KissXML.

Is there a way to prevent app crashing if <thing>false</thing> is <thing/> ?

I am using this code:

if ([[element elementsForName:@"thing"] count] > 0) {
    id obj = [[element elementsForName:@"thing"] objectAtIndex:0];
    if (obj) self.thing = [obj boolValue];
}

Solution

  • Always check these objects, especially because the xml is coming from outside the app and can have unpredictable formatting. You are calling objectAtIndex:, but you don't know how many objects there are.

    if ([[element elementsForName:@"thing"] count] > 0) {
    
       NSArray *elements = [element elementsForName:@"thing"];
    
       id obj = [elements objectAtIndex:0];
    
       NSString *stringValue = [obj stringValue];
    
       BOOL boolValue = FALSE;
    
       if(stringValue) {
         boolValue = [stringValue boolValue];
       }
       self.thing = boolValue;
    }