将浮点值赋给NSMutableArray

时间:2011-10-20 15:13:50

标签: objective-c ios xcode floating-point nsmutablearray

我想在for循环中将float变量赋给nsmutable数组。我是这样做的。但是,nsmutable数组似乎为null。我怎么解决这个问题? (距离是浮点数,enyakinarray是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);

}

4 个答案:

答案 0 :(得分:5)

向数组添加数字 NSArray (NSMutableArray)不允许您向其添加基元类型。这是因为NSArray是一组指向您添加到它的对象的简单指针。这意味着如果要向数组添加数字,首先必须将其包装在NSNumber中。

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

数字类型转换

NSNumber允许您轻松转换数字的类型,例如从int到float

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

答案 1 :(得分:3)

如果数组为null(nil),那么你可能还没有初始化它?

enyakinarray = [[NSMutableArray alloc] init];

不要忘记,如果你分配它,你需要在完成后释放它。

[enyakinarray release];

答案 2 :(得分: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);

答案 3 :(得分:0)

使用CGFloat,我知道它有效。此外,由于我的评论,我被提醒了一些事情。 NSNumber也可以使用,这里是类引用http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnumber_Class/Reference/Reference.html