我正在尝试将Annotations添加到数组中以在地图上放置多个引脚。我把所有东西都放在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];
}
}
答案 0 :(得分:4)
您正在循环中创建一个可变数组并将对象添加到其中。
在循环的下一次迭代中,您将创建一个新的可变数组并为其添加新注释。
不考虑您是从另一个数组创建它而不是仅仅将注释添加到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
}
答案 1 :(得分:0)
您是否尝试过保留实例以避免被释放?
答案 2 :(得分:0)
每次循环时,都会创建一个包含不同数组内容的新可变数组。包含您在上一次迭代中添加的对象的可变数组不会保留。