1

我有一些代码可以找到用户位置并将其返回到标签中。在某些情况下,subAdministrativeArea 或通道不可用,我想修改我的字符串,使其不显示 (null)。我尝试了一些 if 来检查这一点,但如果 (null) 不止一个,则会出现问题。有人对此有任何想法吗?

这是我当前的代码,需要修改以检测地标对象是否等于 null:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        CLLocation *currentLocation = newLocation;
        [location stopUpdatingLocation];

        [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error == nil && [placemarks count] > 0) {
            placemark = [placemarks lastObject];

            countryDetected = placemark.ISOcountryCode;
            placeLabel.text = [NSString stringWithFormat:@"%@, %@, %@, %@, %@ %@", placemark.country, placemark.subAdministrativeArea, placemark.subLocality, placemark.postalCode, placemark.thoroughfare, placemark.subThoroughfare];
            userPlace = [NSString stringWithFormat:@"%@, %@, %@, %@, %@ %@", placemark.country, placemark.subAdministrativeArea, placemark.subLocality, placemark.postalCode, placemark.thoroughfare, placemark.subThoroughfare];

        } else {
            NSLog(@"%@", error.debugDescription);
        }
    } ];
}
4

2 回答 2

2

两种选择:

1) 使用一个NSMutableString并且只附加非零值

2)更新您当前的解决方案,使每个参数如下:

placemark.country ? placemark.country : @"", placemark.subAdministrativeArea ? placemark.subAdministrativeArea : @"", ...

更新:我没有注意到原始问题中的逗号。由于那些在那里,您最好的选择是选项1:

NSMutableString *label = [NSMutableString string];
if (placemark.country) {
    [label appendString:placemark.country];
}
if (placemark.subAdministrativeArea) {
    if (label.length) {
        [label appendString:@", "];
    }
    [label appendString:placemark.subAdministrativeArea];
}
// and the rest
于 2013-04-15T07:25:49.700 回答
2

试试这个..如果placemark.subAdministrativeAreanil那么你可以在if条件中编写自己的字符串,否则将值设置placemark.subAdministrativeArea为字符串变量并将其分配给UILable...

更新:

NSMutableString *strLblTexts = [[NSMutableString alloc] init];
if (placemark.country != nil) {
        [strLblTexts appendString:placemark.country];
}
if (placemark.subAdministrativeArea != nil) {
        if ([strLblTexts isEqualToString:@""]||[strLblTexts isEqual:nil]) {
        [strLblTexts appendString:placemark.subAdministrativeArea];
    }
    else{
        NSString *strtemp=[NSString stringWithFormat:@",%@",placemark.subAdministrativeArea];

        NSLog(@">>>>>>>>>>>>> str temp :%@", strtemp);
        [strLblTexts appendString:strtemp];
    }
}
if (placemark.subLocality != nil) {
        if ([strLblTexts isEqualToString:@""]||[strLblTexts isEqual:nil]) {
        [strLblTexts appendString:placemark.subLocality];
    }
    else{
        NSString *strtemp=[NSString stringWithFormat:@",%@",placemark.subLocality];

        NSLog(@">>>>>>>>>>>>> str temp :%@", strtemp);
        [strLblTexts appendString:strtemp];
    }
}

像另一个 3 字段一样做同样的事情,最后将该值设置为UILable如下所示...

placeLabel.text = strLblTexts;
于 2013-04-15T07:27:35.310 回答