Reputation: 683
I want to assign float variables to nsmutable array in a for loop. I did it like below. But the nsmutable array is seems null. How can I solve this? (distance is float and enyakinarray is 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);
}
Upvotes: 2
Views: 6509
Reputation: 27147
You are creating a new array every iteration of the for loop. You want to do this:
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);
Upvotes: 3
Reputation: 3045
Adding a number to an array
NSArray (NSMutableArray)
doesnt allow you to add primitive types to it. This is because an NSArray is simple a set of pointers to the Objects you add to it. This means if you want to add a number to the array, you first have to wrap it in a NSNumber
.
NSArray *numbers=[NSArray arrayWithObject:[NSNumber numberWithInteger:2]];
Number type conversion
NSNumber allows you to easily convert the type of a number e.g. from an int to a float
NSNumber *number=[NSNumber numberWithInteger:2];
float floatValue = [number floatValue];
Upvotes: 5
Reputation: 3045
Use CGFloat instead, I know that works. Also, I was reminded of something because of the comment below mine. NSNumber will work too, here is the class reference http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnumber_Class/Reference/Reference.html
Upvotes: 0
Reputation: 6522
If the array is null (nil) then maybe you haven't initialised it?
enyakinarray = [[NSMutableArray alloc] init];
Don't forget if you alloc it, you need to release it when finished with it.
[enyakinarray release];
Upvotes: 3