-5

i want to have an array with values "25 kg", "26 kg"... "149 kg", "150 kg". To simplify task i wrote this:

-(NSMutableArray*)weightArray{

    NSMutableArray *myArray;
    for (int i=25; i++; i<150){
        NSString *weightString;
        weightString = [NSString stringWithFormat:@"%d kg", i];
        [myArray addObject:weightString];
    }
    return myArray;
}

And then in viewDidload in my view i wrote: NSLog (@"%@", [self weightArray]); But it looks like it's not working. I might be missing something obvious like syntax. Why is it not working?

UPDATE: Finally i found a solution - first, i declare weightArray in @implementation section, then i wrote:

-(void)fillingArray{

    if (!weightArray){
        for (int i=25; i<150 ;i++){
            NSString *weightString = [[NSMutableArray alloc] init];
            weightString = [NSString stringWithFormat:@"%d kg", i];
            [weightArray addObject:weightString];
            NSLog(@"%@", weightString);
        }
    }

}

In viewDidLoad i wrote:

[self fillingArray];  
 NSLog(@"%@", weightArray);

I think, my problem was in that string NSLog(@"%@", [self weightArray]); In square brackets it suppose to be method name, but i was trying to point at array, and nothing happening.

4

2 回答 2

7

There are 3 problems with what you are doing.

  1. You need to create your array like this: NSMutableArray *myArray = [[NSMutableArray alloc] init]; so that it will actually exist.
  2. Your NSLog needs to be NSLog (@"%@", [self weightArray]); since you are lgging an array and not a number.
  3. (thanks rmaddy for pointing this out) The 2nd and 3rd part of your for statement are reversed. So, i++ is your condition and is always non-zero. This infinite loop is what causes your machine to lock up.

EDIT: Here's a better way that only creates the array once.

-(NSMutableArray*)weightArray{

    static NSMutableArray *myArray;
    if (!myArray){
        myArray = [[NSMutableArray alloc] init];
        for (int i=25; i<150 ;i++){
            NSString *weightString;
            weightString = [NSString stringWithFormat:@"%d kg", i];
            [myArray addObject:weightString];
        }
    }
    return myArray;
}
于 2013-03-30T22:09:46.603 回答
2

You don't allocate and initialize the array. So it has an indeterminate value, and your program invokes undefined beahvior. Create it actually:

NSMutableArray *myArray = [NSMutableArray new];
于 2013-03-30T22:03:29.573 回答