2011-10-20 32 views
2

我想將浮點變量賦值給for循環中的nsmutable數組。我在下面做了。但是nsmutable數組似乎是空的。我該如何解決這個問題? (距離爲float,並且enyakinarray是NSMutableArray的。)將浮點值分配給NSMutableArray

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 = [[NSMutableArray alloc] init]; 
    [enyakinarray addObject:num]; 
    NSLog(@"asasasas %@",enyakinarray); 

} 

回答

3

如果數組爲空(無),那麼也許你還沒有初始化它?

enyakinarray = [[NSMutableArray alloc] init]; 

不要忘記,如果你分配它,你需要釋放它後,它完成。

[enyakinarray release]; 
+0

好吧,當我分配enyakinarray,它每次都會改變。分配過程在for循環中。我想這樣做:重複循環,直到計算另一個數組的數量和距離,並將距離添加到enyakinarray。 –

+0

我想保留在enyakinarray for循環中計算的每個距離。 –

+0

我很樂意提供幫助,但需要查看迄今爲止編寫的代碼。編輯您的原始問題,將更新後的代碼放在當前代碼下。 - 我會看到我能看到的。 –

5

添加一個數字數組 NSArray (NSMutableArray)犯規讓你原始類型添​​加到它。這是因爲NSArray是一組指向您添加到它的對象的指針。這意味着如果你想給數組添加一個數字,你首先必須將其包裝在NSNumber中。

NSArray *numbers=[NSArray arrayWithObject:[NSNumber numberWithInteger:2]]; 

編號類型轉換

的NSNumber讓您輕鬆將數字轉換的類型例如從int到浮點數

NSNumber *number=[NSNumber numberWithInteger:2]; 
float floatValue = [number floatValue]; 
3

您正在for循環的每次迭代中創建一個新數組。你想這樣做:

NSMutableArray *enyakinarray = [[NSMutableArray alloc] init]; 
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);