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



不知道我哪里出错了。我有一个最多包含 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];

如果你知道你的数组中最多只能有 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;

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

最新更新