我是执行应用程序时用户的位置,并且如果位置变量为@(null),则禁止使用if语句。
在My FirstViewController.h:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[super viewDidLoad];
// Do any additional setup after loading the view.
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
}
CLLocationManager *locationManager;
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
CLLocation *currentLocation = newLocation;
if (currentLocation != NULL) {
[(AppDelegate *)[[UIApplication sharedApplication] delegate] setLatitude:[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]];
[(AppDelegate *)[[UIApplication sharedApplication] delegate] setLongitude:[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]];
}
}
在我的SecondViewController上:
-(void) GettingGlobalVariables{
NSString *UsersCurrentLatitude = [(AppDelegate *)[[UIApplication sharedApplication] delegate] latitude];
NSString *UsersCurrentLongitude = [(AppDelegate *)[[UIApplication sharedApplication] delegate] longitude];
NSNumberFormatter * singsingsing = [[NSNumberFormatter alloc] init];
[singsingsing setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumberLatitude = [singsingsing numberFromString:UsersCurrentLatitude];
NSNumberFormatter * sheCameToMeOneMorning = [[NSNumberFormatter alloc] init];
[sheCameToMeOneMorning setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumberLongitude = [sheCameToMeOneMorning numberFromString:UsersCurrentLongitude];
NSLog(@"mynumberlatitude:%@,mynumberlongitude:%@",myNumberLongitude,myNumberLatitude);
if (!myNumberLatitude) {
NSLog(@"location variables are null");
TabBar *TB =[[TabBar alloc]init];
[TB performSelector:@selector(viewDidLoad)];
[TB performSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)];
[self performSelector:@selector(GettingGlobalVariables)];
}
}
使用此if语句,当变量为null时,应用程序会崩溃。有什么建议吗?
最佳答案
这样使用
if (currentLocation != [NSNull null] | currentLocation !=nil) {
//write your code here.
}
关于ios - 我如何避免由于防止变量为@(null)而导致崩溃?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16483645/