开发者

[OBJ-C][iOS] Getting floating point from NSArray - Problem

I’ve recently stuck at a problem. Here is the thing, I’m trying to get a float object from NSArray that holds it, and all I can get is (null). Obviously not the thing that I want to receive. Look at the snippet of code:

h = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:1.0], nil];
x = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:1.0],[NSNumbe开发者_开发知识库r numberWithFloat:2.0], nil]; 
y = [[NSMutableArray alloc] init];

int step = 15; // That is just a random value, will depend on size of h and x.

for (int i = 0; i < step; ++i) {
   NSLog(@"step = %i", i);


 NSMutableArray *xTemp = [[NSMutableArray alloc] initWithArray:x];
 NSMutableArray *hTemp = [[NSMutableArray alloc] initWithArray:h];

 for (int j = 0; j < 3; ++j) {

   float xToMul = [[xTemp objectAtIndex:j] floatValue];
   float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];

   NSLog(@"xToMul = %@", xToMul);
   NSLog(@"hToMul = %@", hToMul);


 }

   NSLog(@"\n");

}

And the resul is:

xToMul = (null)
hToMul = (null)

and all I need those values is to do some easy math.

Thanks. M.R.


Here's your problem:

float xToMul = [[xTemp objectAtIndex:j] floatValue]; float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];
NSLog(@"xToMul = %@", xToMul); NSLog(@"hToMul = %@", hToMul);

%@ is for objects that support -description. float is not an object at all. This code sends the float a -description message, which it can't respond to.

There's two ways to solve this.

The first is to make xToMul and hToMul objects instead of floats and keep the format string.

id xToMul = [xTemp objectAtIndex:j];
id hToMul = [hTemp objectAtIndex:(j+i)];
NSLog(@"xToMul = %@", xToMul);
NSLog(@"hToMul = %@", hToMul);

The second is to keep them as floats but fix the format string:

float xToMul = [[xTemp objectAtIndex:j] floatValue];
float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];
NSLog(@"xToMul = %f", xToMul);
NSLog(@"hToMul = %f", hToMul);

If you're planning to do math with the floats, you probably want to pick this option.

Another interesting point is this loop:

 for (int j = 0; j < 3; ++j) {

This will step through j with three values: 0, 1 and 2. That corresponds to the first, second and third item in NSArray. You have two items in x and three in h. I'm guessing this is just a simplification of your original code, but in both cases it's one short. j of 2+1 will access the 4th item in h, and j of 2 will access the 3rd item in x.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜