2011-10-27 48 views
1

我正在爲nsmutablearray的數據循環做一些操作。但有時工作有時它給我像「數組索引3空數組」錯誤在這行:NSMutableArray空陣列錯誤

else if (min>[[enyakinarray objectAtIndex:i] floatValue]) 

全碼:

for (int i=0; i<[ws3.CustomerID count]; i++) { 

    //radian hesaplaması 
    float total = [first floatValue]; 
    float theta = total * M_PI/180; 
    float total2 = [second floatValue]; 
    float theta2 = total2 * M_PI/180; 
    float total3 = [[ws3.Latitude objectAtIndex: i] floatValue]; 
    float theta3 = total3 * M_PI/180; 
    float total4 = [[ws3.Longitude objectAtIndex: i] floatValue]; 
    float theta4 = total4 * M_PI/180; 


    distance = 6371 * acos(cos(theta) * cos(theta3) 
          * cos(theta4 - theta2) 
          + sin(theta) * sin(theta3)) ; 

    NSLog(@"xxxxx %f",distance); 

    num = [NSNumber numberWithFloat:distance]; 
    [enyakinarray addObject:num]; 
    NSLog(@"asasasas %@",enyakinarray); 

} 

float min; 
NSString *s; 
for (int i=0; i<[enyakinarray count]; i++) { 
    if(i==0) 
    { 
    min = [[enyakinarray objectAtIndex:i] floatValue]; 
    s= [ws3.CustomerName objectAtIndex:i]; 
    } 
    else if (min>[[enyakinarray objectAtIndex:i] floatValue]) 
      { 
      min= [[enyakinarray objectAtIndex:i] floatValue]; 
      s = [ws3.CustomerName objectAtIndex:i]; 
      } 
    enyakinfirma.text=s; 
    } 

我該如何解決這個問題?

+1

你肯定'ws3.CustomerName'包含'[enyakinarray數]'對象? – Nekto

+0

什麼來自日誌聲明? – jrturton

+2

'array index 3 empty array'聽起來不像一個真正的錯誤信息,請發佈你遇到的確切消息。 – DarkDust

回答

1

這很奇怪,但應該很容易調試。只需在您的for之前寫上

NSLog("First array: %@", enyakinarray) 
NSLog(@"Second array: %@", ws3.CustomerName) 
NSLog(@"Second array: %@", ws3.CustomerID) 

並且您應該很快看到問題。也許你正在改變它的創建和使用之間的數組內容?

但是,我在那裏看到一個設計問題。您的代碼使用幾個單獨的陣列CustomerName,CustomerIDenyakinarrayLatitudeLongitude,它們包含單個實體Customer(name,id,緯度,經度和距離)的值。也許你可以用這些屬性創建一個客戶對象,並只保留一個客戶數組?良好的面向對象設計,可以幫助你避免這種類型的錯誤:)

而且你可以在兩個週期合併成一個:


float minDistance = FLT_MAX; 
NSUInteger customerIndex = 0; 

for (NSUInteger i = 0; i < [ws3.CustomerID count]; i++) { 
    /* distance calculation code ... */ 

    float distance = 6371 * acos(cos(theta) * cos(theta3) 
          * cos(theta4 - theta2) 
          + sin(theta) * sin(theta3)); 

    if (distance < minDistance) { 
     minDistance = distance; 
     customerIndex = i; 
    } 
} 

enyakinfirma.text = [ws3.CustomerName objectAtIndex:customerIndex];