想要检查数组是包含所有对象还是仅包含某些对象 - iOS

时间:2013-12-20 01:17:01

标签: ios annotations location nsarray mkpointannotation

不知道我哪里出错了。我有一个包含最多3个对象的数组。我想检查是否有任何数组对象超过0,&如果是,请将它们格式化为NSString。如果没有,我想将对象包含在索引0。

正确方向上的一点很棒!

// 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];

1 个答案:

答案 0 :(得分:0)

如果您知道阵列中最多只能有3条记录,那么您可以做一些天真的事情:

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

然后根据有多少来做你需要的。

你的代码对我来说是你只是在“,”的第一个实例中破坏你的字符串。另一种简单的方法是找到第一个分隔符的范围,然后将字符串剪切成两个子字符串。

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;

如果字幕为零,那么你就知道你没有那部分字符串。