异常“ NSRangeException”,原因:“ ***-[__ NSArray0 objectAtIndex:]:空NSArray的索引0超出范围”

时间:2018-06-28 11:42:54

标签: ios objective-c iphone nsarray

通常,这段代码对我来说非常有效,直到最近我去更新项目以支持最新的iOS,并且在单击地图按钮时收到错误;

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'

在使用Xcode 9之前,它可以正常工作,所以我猜现在代码的工作方式略有不同。

该数组为NSArray *arr_OfCountryCode;

然后我们在viewDidLoad

中对其进行初始化
//Initialize NSArray object with Images

arr_OfCountryCode=@[@"AF",@"AL",@"DZ",@"AS",@"AD",@"AO",@"AI",@"AQ",@"AG",@"AR",@"AM",@"AW",@"AC",@"AU",@"AT",@"AZ",@"BS",@"BH",@"BD",@"BB",@"BY",@"BE",@"BZ",@"BJ",@"BM",@"BT",@"BO",@"BA",@"BW",@"BV",@"BR",@"IO",@"VG",@"BN",@"BG",@"BF",@"BI",@"KH",@"CM",@"CA",@"IC",@",CV",@"BQ",@"KY",@"CF",@"EA",@"TD",@"CL",@"CN",@"CX",@"CP",@"CC",@"CO",@"KM",@"CD",@"CG",@"CK",@"CR",@"HR",@"CU",@"CW",@"CY",@"CZ",@"CI",@"DK",@"DG",@"DJ",@"DM",@"DO",@"EC",@"EG",@"SV",@"GQ",@"ER",@"EE",@"ET",@"FK",@"FO",@"FJ",@"FI",@"FR",@"FG",@"PF",@"TF",@"GA",@"GM",@"GE",@"DE",@"GH",@"GI",@"GR",@"GL",@"GD",@"GP",@"GU",@"GT",@"GG",@"GN",@"GW",@"GY",@"HT",@"HM",@"HN",@"HK",@"HU",@"IS",@"IN",@"ID",@"IR",@"IQ",@"IE",@"IM",@"IL",@"IT",@"JM",@"JP",@"JE",@"JO",@"KZ",@"KE",@"KI",@"XK",@"KW",@"KG",@"LA",@"LV",@"LB",@"LS",@"LR",@"LY",@"LI",@"LT",@"LU",@"MO",@"MK",@"MG",@"MW",@"MY",@"MV",@"ML",@"MT",@"MH",@"MQ",@"MR",@"MU",@"YT",@"MX",@"FM",@"MD",@"MC",@"MN",@"ME",@"MS",@"MA",@"MZ",@"MM",@"NA",@"NR",@"NP",@"NL",@"NC",@"NZ",@"NI",@"NE",@"NG",@"NU",@"NF",@"KP",@"MP",@"NO",@"OM",@"PK",@"PW",@"PS",@"PA",@"PG",@"PY",@"PE",@"PH",@"PN",@"PL",@"PT",@"PR",@"QA",@"RO",@"RU",@"RW",@"RE",@"WS",@"SM",@"SA",@"SN",@"RS",@"SC",@"SL",@"SG",@"SX",@"SK",@"SI",@"SB",@"SO",@"ZA",@"GS",@"KR",@"SS",@"ES",@"LK",@"BL",@"SH",@"KN",@"LC",@"MF",@"PM",@"VC",@"SD",@"SR",@"SJ",@"SZ",@"SE",@"CH",@"SY",@"ST",@"TW",@"TJ",@"TZ",@"TH",@"TL",@"TG",@"TK",@"TO",@"TT",@"TA",@"TN",@"TR",@"TM",@"TC",@"TV",@"UM",@"VI",@"UG",@"UA",@"AE",@"GB",@"US",@"UY",@"UZ",@"VU",@"VA",@"VE",@"VN",@"WF",@"EH",@"YE",@"ZM",@"ZW",@"AX"];

当用户点击按钮时,会在actionMethod中随机显示地图上的位置;

str_Type = @"Randum";
        self.mapView.hidden = NO;
        int randomIndex = arc4random() % [arr_OfCountryCode count];
        NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false",[arr_OfCountryCode objectAtIndex:randomIndex]];

        NSURL *url = [[NSURL alloc] initWithString:urlString];

我正在为数组在最新版本之前可用于多个iOS版本和设备而为何将数组分类为空而苦苦挣扎。

当我在Xcode中检查它时,它显示为nil,其他数组在初始化之前都没有问题,我什至尝试复制一个现有数组,将其重命名为*arr_OfCountryCode;,但仍然显示为nil

在这种方法中(下面有整个文章),我相信是问题所在。

- (IBAction)actionMethod:(UIButton *)sender {
    if ([sender tag] == 0) {
        self.musicView.hidden = NO;
        [self.tbl_MusicTable reloadData];
    } else if ([sender tag] == 1) {
        str_Type = @"Randum";
        self.mapView.hidden = NO;
        int randomIndex = arc4random() % [arr_OfCountryCode count];
        NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=false",[arr_OfCountryCode objectAtIndex:randomIndex]];

        NSURL *url = [[NSURL alloc] initWithString:urlString];

        [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

            if (error) {
                NSLog(@"%@",error.description);
            } else {

                NSDictionary *jsonObject=[NSJSONSerialization
                                          JSONObjectWithData:data
                                          options:NSJSONReadingMutableLeaves
                                          error:nil];

                NSDictionary *places = [[[[jsonObject objectForKey:@"results"] objectAtIndex:0] objectForKey:@"geometry"] objectForKey:@"location"];
                NSDictionary *locations = [[[jsonObject objectForKey:@"results"] objectAtIndex:0] objectForKey:@"address_components"];

                float lat = [[places objectForKey:@"lat"] floatValue];
                float lon = [[places objectForKey:@"lng"] floatValue];

                MKCoordinateRegion region;
                MKCoordinateSpan span;
                span.latitudeDelta = 0.50;
                span.longitudeDelta = 0.50;

                location.latitude = lat;
                location.longitude = lon;
                region.span = span;
                region.center = location;
                [self.mk_MapView setRegion:region animated:YES];

                NSString *str_Title = [[locations valueForKey:@"long_name"] objectAtIndex:0];
                NSString *str_Short = [[locations valueForKey:@"short_name"] objectAtIndex:0];

                MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
                point.coordinate = location;
                point.title = str_Title;
                point.subtitle = str_Short;
                [self.mk_MapView addAnnotation:point];




            }
        }];
    }
}

进一步的核心定位代码在这里

#pragma mark - CLLocationManager Delegate Method
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    if ([str_Type isEqualToString:@"Custom"]) {
        CLLocation *currentLocation = newLocation;
        NSString *str_Longitude;
        NSString *str_Latitude;
        MKCoordinateRegion region;
        MKCoordinateSpan span;
        span.latitudeDelta = 0.020;
        span.longitudeDelta = 0.020;
        location.latitude = currentLocation.coordinate.latitude;
        location.longitude = currentLocation.coordinate.longitude;
        region.span = span;
        region.center = location;
        [self.mk_MapView setRegion:region animated:YES];

        if (currentLocation != nil) {
            str_Longitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
            str_Latitude = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
        }

        // Reverse Geocoding
        [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            if (error == nil && [placemarks count] > 0) {
                placemark = [placemarks lastObject];
                MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
                point.coordinate = currentLocation.coordinate;
                point.title = placemark.country;
                point.subtitle = placemark.locality;
                [self.mk_MapView addAnnotation:point];
            } else {
                NSLog(@"%@", error.debugDescription);
            }
        } ];
    } else {
        MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
        point.coordinate = location;
        point.title = placemark.country;
        point.subtitle = placemark.locality;
        [self.mk_MapView addAnnotation:point];
    }
}

#pragma mark - MKMapView Delegate Methods
-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView *pinView = nil;
    if(annotation != self.mk_MapView.userLocation)
    {
        static NSString *defaultPinID = @"com.invasivecode.pin";
        pinView = (MKAnnotationView *)[self.mk_MapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if ( pinView == nil )
            pinView = [[MKAnnotationView alloc]
                       initWithAnnotation:annotation reuseIdentifier:defaultPinID];

        //pinView.pinColor = MKPinAnnotationColorGreen;
        pinView.canShowCallout = YES;
        //pinView.animatesDrop = YES;
        pinView.image = [UIImage imageNamed:@"HesOnThisMap"];    //
    }
    else {
        //[self.mk_MapView.userLocation setTitle:@"I am here"];
    }
    return pinView;
}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    MKAnnotationView *aV;
    for (aV in views) {
        CGRect endFrame = aV.frame;
        aV.frame = CGRectMake(aV.frame.origin.x, aV.frame.origin.y - 230.0, aV.frame.size.width, aV.frame.size.height);
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.45];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [aV setFrame:endFrame];
        [UIView commitAnimations];
    }
}

1 个答案:

答案 0 :(得分:0)

这与google maps api回调有关,当它达到最大回调时崩溃了