0

I'm working on an Mac OS X application which deals with records from an MySQL database server. I'm fetching data with the help of the MySQL C API and create an NSMutableArray for the result. Each fetched record creates an NSDictionary, which is added to the NSMutableArray.

What is the best way to handle empty number values returned by the database server? Since nil can't be inserted into an NSDictionary, I tried several solutions like associated objects to "mark" an NSNumber as NULL, using [NSNull null], or even subclassing NSNumber. But the most simple solution I found was creating an NSNumber with a double value of zero divided by zero, like this:

// for each row in the MySQL result check the field type and create the ObjC value
...
case MYSQL_TYPE_DOUBLE: {
  if (row[col] == NULL) {   // row is the last fetched MYSQL_ROW
    [record setObject:[NSNumber numberWithDouble:0.0/0.0] forKey:columnNames[col]];
  } else {
    [record setObject:@(strtod(row[col], NULL)) forKey:columnNames[col]];
  }
  break;
}
...

This allows for an easy test against NSDecimalNumber's notANumber property and also the use of
NSNumberFormatter's notANumberSymbol to format empty values in the UI.

Are there any drawbacks to do it that way?

2 Answers 2

0

I would create the NaN number different:

[NSDecimalNumber notANumber]

The division by zero leads to an undefined state, if I remember the standard correct.

But beside this I think, that it is okay.

0

Since you're using an associative array, you don't need to set it as nil, skipping over the key instead will result in the returned object for that key being nil, which takes less code to compare as opposed to notANumber. Like so:

 case MYSQL_TYPE_DOUBLE: {
    if (row[col])
      [record setObject:@(strtod(row[col], NULL)) forKey:columnNames[col]];
    }
    break;

}

1
  • I have to assign a value for all columns. Bindings will work with nil, but observerValueForKeyPath: will not.
    – user1360618
    Aug 15, 2013 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.