исключение 'NSRangeException', причина: '*** - [__ NSArray0 objectAtIndex:]: индекс 0 вне границ для пустого NSArray' - PullRequest
0 голосов
/ 28 июня 2018

обычно этот код работал отлично для меня, до недавнего времени я ходил обновлять свой проект для поддержки последней версии 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 и устройств.

Отображается как nil, как только я проверяю его в Xcode, другие массивы инициализируются перед ним без проблем, я даже пытался скопировать существующий массив, переименовав его в *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];




            }
        }];
    }
}

Дополнительный код для corelocation находится здесь

#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 голосов
/ 06 июля 2018

Это было связано с обратными вызовами API Google Maps, он падал, когда достиг максимальных обратных вызовов

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...