NSMutableArray, кажется, преждевременно выпускает - PullRequest
0 голосов
/ 28 января 2012

Я пытаюсь добавить аннотации в массив, чтобы разместить несколько пинов на карте.У меня все в цикле.В первый раз, когда он проходит, он добавляет объект в массив просто отлично.Когда он возвращается ... массив содержит 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];
 }
}

Ответы [ 3 ]

4 голосов
/ 28 января 2012

Вы создаете изменяемый массив в цикле и добавляете в него свой объект.

На следующей итерации цикла вы создаете новый изменяемый массив и добавляете в него новую аннотацию.

Оставьте в стороне тот факт, что вы создаете его из другого массива, а не просто добавляете аннотацию к 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
}
0 голосов
/ 28 января 2012

Каждый раз в цикле вы создаете новый изменяемый массив с содержимым другого массива. Изменяемый массив, содержащий объект, добавленный вами на предыдущей итерации, не сохраняется.

0 голосов
/ 28 января 2012

Вы пытались сохранить экземпляр, чтобы избежать его выпуска?

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