我正在尝试将注释添加到数组以在地图上放置多个图钉。我将所有内容都放在for循环中。第一次循环通过时,就可以将对象添加到数组中。当它返回时...数组中有0个对象。谁能告诉我为什么?
编辑:我正在使用ARC。
-(void)plotMultipleLocs {
float latitude;
float longitude;
NSRange commaIndex;
NSString *coordGroups;
for (int i=0; i<=cgIdArray.count; i++) {
coordGroups = [cgInAreaArray objectAtIndex:i];
commaIndex = [coordGroups rangeOfString:@","];
latitude = [[coordGroups substringToIndex:commaIndex.location] floatValue];
longitude = [[coordGroups substringFromIndex:commaIndex.location + 1] floatValue];
CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(latitude, longitude);
MKCoordinateRegion reg = MKCoordinateRegionMakeWithDistance(loc, 1000, 1000);
self->mapView.region = reg;
MKPointAnnotation* ann = [[MKPointAnnotation alloc] init];
ann.coordinate = loc;
ann.title = [cgNameArray objectAtIndex:i];
ann.subtitle = [cgLocArray objectAtIndex:i];
NSMutableArray *mutAnnArray = [NSMutableArray arrayWithArray:annArray];
[mutAnnArray addObject:ann];
}
}
最佳答案
您正在循环内创建一个可变数组并将对象添加到其中。
在循环的下一次迭代中,您将创建一个新的可变数组,并为其添加新的注释。
抛开您正在从另一个数组创建它的事实,而不只是将注释添加到annArray
基本上,要添加对象的数组将持续一次迭代,然后超出范围。
尝试将数组移出循环:
-(void)plotMultipleLocs {
float latitude;
float longitude;
NSRange commaIndex;
NSString *coordGroups;
NSMutableArray *mutAnnArray = [NSMutableArray arrayWithArray:annArray]; // Create one array outside the loop.
for (int i=0; i<=cgIdArray.count; i++) {
coordGroups = [cgInAreaArray objectAtIndex:i];
commaIndex = [coordGroups rangeOfString:@","];
latitude = [[coordGroups substringToIndex:commaIndex.location] floatValue];
longitude = [[coordGroups substringFromIndex:commaIndex.location + 1] floatValue];
CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(latitude, longitude);
MKCoordinateRegion reg = MKCoordinateRegionMakeWithDistance(loc, 1000, 1000);
self->mapView.region = reg;
MKPointAnnotation* ann = [[MKPointAnnotation alloc] init];
ann.coordinate = loc;
ann.title = [cgNameArray objectAtIndex:i];
ann.subtitle = [cgLocArray objectAtIndex:i];
[mutAnnArray addObject:ann]; // Add the annotation to the single array.
}
// mutAnnArray will go out of scope here, so maybe return it, or assign it to a property
}
关于iphone - NSMutableArray似乎过早发布,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9039468/