我有一个自定义类,它有一个坐标的实例变量:
CLLocationCoordinate2D eventLocation;
@property(nonatomic) CLLocationCoordinate2D eventLocation;
我正在解析一个 xml 文件,该文件有一个可选字段,该字段可能存在也可能不存在。 如果是我这样设置:
CLLocationCoordinate2D location;
NSArray *coordinateArray = [paramValue componentsSeparatedByString:@","];
if ([coordinateArray count] >= 2) {
location.latitude = [[coordinateArray objectAtIndex:0] doubleValue];
location.longitude = [[coordinateArray objectAtIndex:1] doubleValue];
} else {
NSLog(@"Coordinate problem");
}
info.eventLocation = location;
我所做的基本上是在 map 上添加注释
annotation.coordinate = alert.info.eventLocation;
我知道我需要在这里做一些检查以确保它存在,但我不允许执行 if (info.eventLocation == nil)
甚至 if ( info.eventLocation.latitude == nil)
这似乎是一个非常基本的问题,但我已经进行了一些搜索,但没有人能够真正提供一个好的答案/想法。我的架构完全不对吗?
最佳答案
因为 CLLocationCoordinate2D
是一个结构,所以不存在 nil
值这样的东西。如果结构是对象实例变量,Objective-C 会将结构初始化为 0,因此如果您没有为 eventLocation
、annotation.coordinate.longitude
和 设置值eventLocation.lattitude
都将为 0。由于这是一个有效的位置,因此它不是一个有用的标记。
我会定义一个非物理值:
static const CLLocationDegrees emptyLocation = -1000.0;
static const CLLocationCoordinate2D emptyLocationCoordinate = {emptyLocation, emptyLocation}
然后将此值分配给您的 alert.info.eventLocation = EmptyLocationCoordinate
以表示一个空值。然后您可以检查 (alert.info.eventLocation == emptyLocationCoordinate)
。
关于iphone - 处理 Objective-C 中的空结构(自定义类中的坐标),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1663276/