2011-10-20 35 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);