locationManager避免(null)string在一个标签

我有一些代码,find用户的位置,并将其返回到标签。 在某些情况下,subAdministrativeArea不可用或通道,我想修改我的string,所以它不显示(空)。 我尝试了一些如果检查这一点,但如果(空)不止一个是有问题的。 任何人都有这个想法?

这是我目前的代码,需要修改,以检测地标对象是否等于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); } } ]; } 

尝试这一个..如果placemark.subAdministrativeAreanil那么你可以编写自己的string,如果条件,否则将UILable的值设置为stringvariables,并将其分配给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一样的波纹pipe。

 placeLabel.text = strLblTexts; 

两个选项:

1)使用NSMutableString ,只附加非零值

2)更新您的当前解决scheme,使每个参数是这样的:

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

更新:我没有注意到原来的问题中的逗号。 由于那些在那里,你最好的select是选项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