NSMutableArray似乎过早地释放了

我正在尝试将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];
 }
}
采纳答案:

您正在循环中创建一个可变数组并将对象添加到它。

在循环的下一次迭代中,您将创建一个新的可变数组并为其添加新注释。

抛开你从另一个数组创建它而不是仅仅将注释添加到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
}
author: abizern

参考更多解答: NSMutableArray seems to be prematurely releasing ,转载请保留出处NSMutableArray似乎过早地释放了及作者信息

Statement: We respect knowledge and authors. Since the content comes from the Internet and is intended for scientific research, any reprinters should retain the author's signature and origin. If you are the author of the content and feel in dispute, please contact email: 1076545519@qq.com. We will find out the situation and deal with it in time. We sincerely thank the author for his hard work.


更多:nsmutablearray