2011-08-19 7 views
0

가변 배열에 객체를 추가하는 중 이상한 문제가있는 것 같습니다. 것은 내가 외부 데이터베이스에서 얻은 좌표와 사전의 배열을 가지고 있으며, 그들을 통해 루프를 할 좌표를 추출, 사용자 정의 주석 객체를 생성하고 다음 변경할 배열에 추가하려고합니다.Cocoa : 루프에서 가변 배열에 객체를 추가하는 중 오류가 발생했습니다.

문제는 그 쇼에서 그들을 얻을 배열은 단 1 개체가 첫 번째 배열 5.

을 가지고 도와주세요! 여기

코드 (비고 : testArray 내가 그것을 노호 작성하지 않습니다 내 클래스의 속성은, 난 그냥 개체를 저장하는 데 사용하려고입니다)입니다

감사합니다!

int times; int count;

count=[theResults count]; 

// do the loop oh yeah do the loop 

for (times=0;times<count; times=times+1) 
{ 
// create dictionary with contents of array 

NSDictionary * testDict = [theResults objectAtIndex:times]; 

NSLog(@"the results has %i objects", [theResults count]); 


NSLog(@"object latitude is %@",[radarDict valueForKey:@"radarLatitude"]); 
NSLog(@"object longitude is %@", [radarDict valueForKey:@"radarLongitude"]); 


double testLatitude=[[radarDict valueForKey:@"radarLatitude"] doubleValue]; 
double testLongitude=[[radarDict valueForKey:@"radarLongitude"] doubleValue]; 

CLLocationCoordinate2D testCoordinate; 
testCoordinate.longitude=testLongitude; 
testCoordinate.latitude=testLatitude; 

    CustomAnnotations* tempAnnotation = [[CustomAnnotations alloc] initWithLocation:testCoordinate]; 

    testArray = [[NSMutableArray alloc] initWithCapacity:count]; 

    [testArray addObject:tempAnnotation];   
    [tempAnnotation release]; 
} 

답변

0

당신은 루프를 실행할 때마다 멀리 배열 폭파 있습니다 : 당신이 당신의 루프에 가기 전에

, 뭔가 좋아한다. 이 줄이 당신을 죽이고 있습니다 :

testArray = [[NSMutableArray alloc] initWithCapacity:count]; 

루프가 시작되기 전에 그것을 넣으면됩니다.

+0

감사합니다. 방금 그걸 봤어. 그 명백한 예치 그러나 그것은 나를 위해 없었다 :) 감사 – Daniel

+0

걱정 없음, 우리 모두는 그 종류의 재료를한다 :) – sosborn

1

문제는 사용자가 배열에 이러한 항목을 추가하지 않고 대신 항상 새로운 배열을 만들고 이전 배열을 덮어 쓰는 것입니다. 그런 다음 해당 새 배열에 항목을 추가하고 계속합니다. 따라서 카운트 - 1 누출 된 배열과 최종 배열을 각각 하나의 항목으로 갖게됩니다.

[testArray autorelease]; 
testArray = [[NSMutableArray alloc] initWithCapacity:count]; 
// start the loop 
for(/* ... */) { 
    // stuff 
    [testArray addObject:tempAnnotation]; 
    // etc... 
} 
0

Sosborn의 대답은 정확하며 배열을 한 번 초기화하고 각 반복을 통해 덮어 쓰지 않도록해야합니다.

미래에 당신에게 유리할 어레이의 반복에 관한 한 가지를 추가하고 싶습니다. 배열에는 열거 자 (enumerator)가 있고 for 루프 구문은 열거 자 기술과 전통적인 for 구문을 사용하여 매우 단순화 될 수 있다는 사실을 고려하십시오.

for (NSDictionary *testDict in theResults) 
{ 
    //Do what you need to with an instance of a dictionary from the array 
} 

이것은 당신이 먼저 배열의 항목 수를 찾을 필요가 없기 때문에 쉽게 만드는 :

은 내가 논의하고있는 방식으로 코드를 단순화했습니다. 반복되는 횟수는 자동으로 결정됩니다. 또한 루프의 조건문을 올바르게 처리하거나 추적 할 int를 증가시키는 작업을 담당하지 않습니다. 이것이 도움이된다고 생각한다면 투표를하십시오.

관련 문제