如何避免因为阻止变量为@(null)而导致崩溃?

时间:2013-05-10 13:39:56

标签: ios if-statement crash location

我在执行应用程序时获取用户位置,如果位置变量是@(null)我阻止了whit 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时应用程序压缩。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

像这样使用,

    if (currentLocation != [NSNull null] | currentLocation !=nil) {
         //write your code here.
    }