Search code examples
iphoneobjective-cxcodeloopsviewdidload

viewDidLoad becomes an infinite loop. HELP


This is probably the easiest/lamest question.

So I am trying to initialize an array with values 0 to 3 increments of 0.25 in the viewDidLoad method, and I can see an infinite loop here.

NSArray *pickArray3 = [[NSMutableArray alloc] init];
int i = 0;
//for(i = 0.25; i<=3; i=i+0.25) 
while (i<3)
{ 
//NSString *myString = [NSString stringWithFormat:@"%d", i]; 
    i=i+0.25;
    NSLog(@"The Value of i is %d", i );
//[pickArray3 addObject:myString]; // Add the string to the tableViewArray.
 }
NSLog(@"I am out of the loop now");
self.doseAmount=pickArray3;
[pickArray3 release];

And This is the Output.

   2011-06-01 11:49:30.089 Tab[9837:207] The Value of i is 0
   2011-06-01 11:49:30.090 Tab[9837:207] The Value of i is 0
   2011-06-01 11:49:30.091 Tab[9837:207] The Value of i is 0
   2011-06-01 11:49:30.092 Tab[9837:207] The Value of i is 0
   // And this goes on //   
   // I am out of the loop now does not get printed //

Solution

  • Your i is an integer, it will never increment adding 0.25. Use a float or double.

    **float** i = 0;
    //for(i = 0.25; i<=3; i=i+0.25) 
    while (i<3)
    { 
    //NSString *myString = [NSString stringWithFormat:@"**%f**", i]; 
        i=i+0.25;
        NSLog(@"The Value of i is **%f**", i );
    //[pickArray3 addObject:myString]; // Add the string to the tableViewArray.
     }