我正在开发一个处理来自MySQL数据库服务器的记录的 Mac OS X 应用程序。我在MySQL C API的帮助下获取数据并为结果创建一个NSMutableArray。每条获取的记录都会创建一个NSDictionary,并将其添加到NSMutableArray中。
处理数据库服务器返回的空数值的最佳方法是什么?由于 nil 不能插入到NSDictionary 中,我尝试了几种解决方案,例如关联对象将NSNumber “标记”为NULL,使用[NSNull null],甚至子类化NSNumber。但我发现的最简单的解决方案是创建一个NSNumber,其双值为零除以零,如下所示:
// 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;
}
...
这允许对 NSDecimalNumber 的 notANumber 属性进行简单的测试,也可以使用
NSNumberFormatter 的 notANumberSymbol 来格式化 UI 中的空值。
这样做有什么缺点吗?