ios - 我如何避免由于防止变量为@(null)而导致崩溃?

标签 ios if-statement crash location

我是执行应用程序时用户的位置,并且如果位置变量为@(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/

相关文章:

javascript - 如何检查输入字段值是否包含字符?

android - 在 Android 2.2 中使用带有 Activity 的 fragment 时应用程序崩溃

Eclipse 崩溃,ieframe.dll

ios - 存折通证制作

ios - Xcode 9. 界面生成器。已安装的复选标记丢失

ios - 您可以使用与开发者帐户不同的帐户提交到应用商店吗

ios - NSFetchedResultsController 似乎正在将空对象插入数组?

python - While 循环、if-else 语句 : Guess my number game

c++ - 使这个具有多个条件的 if 语句更短的方法?

ios - 应用程序在 iOS 8.4 上崩溃