2

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];
}
btype
  • 1,593
  • 19
  • 32

1 Answers1

2

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;
}
Marcel
  • 6,393
  • 1
  • 30
  • 44
  • You are doing the same thing twice. From my point of view it is exactly the same code that I wrote. Line 2 is equal line 1 so no need to check this twice and if you delete line 2 and 3 you got my code. – btype May 24 '13 at 16:39
  • in that case, calling `boolValue` on a nil object would just return FALSE. Where is this code crashing? – Marcel May 24 '13 at 17:00
  • It crashes on boolValue and it is not nil it is an DDXMLElement reading `` in lldb console. I just wanted to know if there is a way to check if it has a value or not. And it says `cannot call boolValue on DDXMLElement` – btype May 24 '13 at 17:58
  • 2
    I dont think boolValue is a method on DDXMLElement or DDXMLNode, maybe use stringValue and check for nil, before calling boolValue on the string object? – Marcel May 24 '13 at 19:09
  • I'll try this out on monday. Good thought! – btype May 24 '13 at 19:49