2011-08-19 36 views
0

嘗試將對象添加到可變數組時,似乎有一個奇怪的問題。事情是我有一個字典數組,我從外部數據庫獲得座標,我嘗試通過它們循環,提取座標,創建一個自定義註釋對象,然後將其添加到可變數組中。可可:將對象從循環添加到可變數組時出錯

的問題是數組我讓他們在表明,只有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

你的問題是,你不添加這些項目到您的陣列,而不是要創建一個新的數組,每次和過寫舊的。然後,將一個項目添加到該新陣列並繼續。因此,您將有count - 1泄漏數組和最終數組,每個都有一個項目。

你進入你的循環之前,做這樣的事情:

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

Sosborn的答案是正確的,你需要做的就是確保你的數組初始化一次,並且每次迭代都不會覆蓋它。

我想添加一件關於數組迭代的內容,我認爲這對您將來有利。考慮一下這樣一個事實,即數組擁有枚舉器,並且使用枚舉器技術與傳統的語法可以非常簡化for循環語法。

我已經簡化你的代碼的方式我討論:

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

這只是更容易,因爲你不必先找出數組中的項目數。它會自動知道它應該迭代多少。此外,您不負責獲取正確的循環條件語句或處理增加int來跟蹤。如果您認爲這有幫助,請投票。