NSArrayI objectAtIndex:]:索引7超出边界[0 .. 6]

时间:2017-02-17 11:46:06

标签: ios objective-c nsarray

我在运行应用程序时在我的应用程序中开发IOS App。 App Run完美。但是数组长度不计入每个。如何计算每个的数组长度。在此先感谢。

这是错误..

'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 7 beyond bounds [0 .. 6]'

代码

- (void)viewDidLoad {
    [super viewDidLoad];
    count = 0;
    marker = [[GMSMarker alloc] init];
    marker.position = camera.target;
    marker.snippet = @"Jalandhar";
    marker.map = mapView;
    self.view = mapView;
    timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(updateLocation:) userInfo:nil repeats:YES];
}

- (void)updateLocation:(NSTimer *)timer {
    [mapView clear];

    NSMutableArray *longitute = [[NSMutableArray alloc]init];
    NSDictionary *latLongDict = @{@"lat": @[@"31.3062", @"31.3107",@"31.3102",@"31.3194",@"31.3312",@"29.9083",@"31.2941",],@"long": @[@"75.5935", @"75.6061",@"75.6117",@"75.5845",@"75.5908",@"75.7299",@"75.5844",]};
    [longitute addObject:latLongDict];

    for (NSDictionary *dic in longitute) {
        NSString *val = [[dic valueForKey:@"lat"]objectAtIndex:count];
        NSString *value = [[dic valueForKey:@"long"]objectAtIndex:count];
        NSLog(@"%@",val);
        NSLog(@"%@",value);
        [CATransaction begin];
        [CATransaction setValue:[NSNumber numberWithFloat: 2.0] forKey:kCATransactionAnimationDuration];

        CLLocationCoordinate2D center;
        center.latitude=[val doubleValue];
        center.longitude=[value doubleValue];
        marker = [[GMSMarker alloc] init];
        marker.position = center;
        marker.map = mapView;
        self.view = mapView;
        [CATransaction commit];
        count++;
    }
}

2 个答案:

答案 0 :(得分:0)

调用updateLocation方法的计时器已设置repeats:YES,因此每2秒调用一次。

您正在count++;方法中增加for循环中的计数updateLocation。但是,您只能在viewDidLoad中重置一次计数。所以第一次调用运行得很好,但下一次调用将失败,索引越界。

count = 0;方法[map clear]下方添加updateLocation以解决问题

答案 1 :(得分:0)

count循环之前将foreach重置为0,以便您的代码如下:

count = 0 // Reset count to zero before the foreach loop
for (NSDictionary *dic in longitute) {
        NSString *val = [[dic valueForKey:@"lat"]objectAtIndex:count];
        NSString *value = [[dic valueForKey:@"long"]objectAtIndex:count];
        NSLog(@"%@",val);
        NSLog(@"%@",value);
        [CATransaction begin];
        [CATransaction setValue:[NSNumber numberWithFloat: 2.0] forKey:kCATransactionAnimationDuration];

        CLLocationCoordinate2D center;
        center.latitude=[val doubleValue];
        center.longitude=[value doubleValue];
        marker = [[GMSMarker alloc] init];
        marker.position = center;
        marker.map = mapView;
        self.view = mapView;
        [CATransaction commit];
        count++;
}