2009-11-02 26 views
9

我具备拥有的实例变量的自定义类的坐标:处理空结构在Objective-C(定制类坐标)

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; 

我做的这基本上是一个地图

annotation.coordinate = alert.info.eventLocation; 

我知道我需要做一些检查这里以确保该上添加注解存在但我不允许做if (info.eventLocation == nil)甚至if (info.eventLocation.latitude == nil)

这似乎是一个非常基本的问题,但我做了一些搜索,没有人能够真正提供一个很好的答案/想法。我的架构完全关闭了吗?

回答

24

因为CLLocationCoordinate2D是一个结构体,所以不存在nil值。如果Objective-C是对象实例变量,它将初始化为0,所以如果你没有为eventLocation设置一个值,那么annotation.coordinate.longitudeeventLocation.lattitude都将为0.因为这是一个有效的位置,所以它不是一个有用的标记。

我会定义一个非phyical值:

static const CLLocationDegrees emptyLocation = -1000.0; 
static const CLLocationCoordinate2D emptyLocationCoordinate = {emptyLocation, emptyLocation} 

,然后分配这个价值,你的alert.info.eventLocation = EmptyLocationCoordinate代表空值。然后您可以检查是否(alert.info.eventLocation == emptyLocationCoordinate)

+0

当我加入这个我我的自定义对象的.h文件中遇到错误: 初始值设定元素不是常数 (近初始化为“EmptyLocationCoordinate.latitude”) 初始值设定元素不是常数 ('EmptyLocationCoordinate.longitude'的初始化附近) – aleclerc 2009-11-02 20:10:37

+0

实际上, alert.info.eventLocation = EmptyLocationCoordinate 仍然会给出“无效操作数为二进制!=”错误 – aleclerc 2009-11-02 20:55:36

+0

啊,也许你需要#define EmptyLocation。 – 2009-11-02 21:22:18

4

我用上面除了它不会让我申报与另一个const的一个const的代码,所以我只是把它改为:

static const CLLocationDegrees EmptyLocation = -1000.0; 
static const CLLocationCoordinate2D EmptyLocationCoordinate = {-1000.0, -1000.0}; 

我在初始化还增加了类:

eventLocation = EmptyLocationCoordinate; 

感谢您的帮助巴里。

3

只是为了完整起见,您可以使用kCLLocationCoordinate2DInvalid常数来保存对无效CLLocationCoordinate2D的引用。 (参见:@Klaas's answer