Pergunta

Not sure where I'm going wrong. I have an array that contains up to 3 objects. I want to check if any of the arrays objects go on past 0, & if so, format them as an NSString. If not, I want to include the object at index 0.

A point in the right direction would be great!

// add annotation
MKPointAnnotation *point = [MKPointAnnotation new];
point.coordinate = (CLLocationCoordinate2D){[self.eventPlan.location_lat doubleValue], [self.eventPlan.location_lng doubleValue]};
NSArray *locationA = [self.eventPlan.location_address componentsSeparatedByString:@", "];
point.title = locationA[0];

if ([locationA containsObject:locationA[1]]) {
    point.subtitle = [NSString stringWithFormat:@"%@, %@", locationA[1], locationA[2]];
} else {
    point.subtitle = [NSString stringWithFormat:@"%@", locationA[1]];
}

[mapView addAnnotation:point];
Foi útil?

Solução

If you know that there can only be at most 3 records in your array you could do something naive like:

switch([locationA count])
{
    case 0:
        ...
        break;
    case 1:
        ...
        break
    case 2:
        ...
        break;
    case 3:
        ...
        break;
}

Then do what you need based on how many there are.

What your code looks like to me is that you are just breaking your string at the first instance of ", ". Another easy way to do that would be to find the range of the first separator, then clipping the string into two substrings.

NSRange range = [string rangeOfString:@", "];
int locationInString = range.location;
if(locationInString != NSNotFound)
{
    point.title = [string substringToIndex:locationInString];
    point.subtitle = [string substringFromIndex:locationInString + 2];
}
else
    point.title = string;

With this if the subtitle is nil then you know you didn't have that portion of the string.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top