Handle empty structs in Objective-C (Coordinate in custom class)
I have a custom class that has as an instance variable of a coordinate:
CLLocationCoordinate2D eventLocation;
@property(nonatomic) CLLocationCoordinate2D eventLocation;
I'm parsing an xml file that has an optional field that may or may not be there. If it is i set it like so:
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;
What I do this is basically add an annotation on a map
annotation.coordinate = alert.info.eventLocation;
I know I need to do some checking here to make sure that that exists but I'm not allowed to do a if (info.eventLocation == nil)
or even if (info.eventLocation.latitude == nil)
This seems like a very basic question but I've done some searching and no one's been able to really provide a good answer/idea. Is my architecture开发者_开发知识库 completely off?
Because CLLocationCoordinate2D
is a struct, there's not such thing as a nil
value. Objective-C will initialize structs to 0 if they are object instance variables, so if you don't set a value for eventLocation
, annotation.coordinate.longitude
and eventLocation.lattitude
will both be 0. Since this is a valid location, it's not a useful marker.
I would define a non-phyical value:
static const CLLocationDegrees emptyLocation = -1000.0;
static const CLLocationCoordinate2D emptyLocationCoordinate = {emptyLocation, emptyLocation}
and then assign this value to your alert.info.eventLocation = EmptyLocationCoordinate
to represent an empty value. You can then check if (alert.info.eventLocation == emptyLocationCoordinate)
.
I used the code above except it wouldn't let me declare a const with another const, so i simply changed it to:
static const CLLocationDegrees EmptyLocation = -1000.0;
static const CLLocationCoordinate2D EmptyLocationCoordinate = {-1000.0, -1000.0};
I also added in my init for the class:
eventLocation = EmptyLocationCoordinate;
Thanks for the help Barry.
Just for completeness sake, you can use the kCLLocationCoordinate2DInvalid
constant to hold a reference to an invalid CLLocationCoordinate2D
. (see: @Klaas's answer)
精彩评论