-1

How do you add every number between 1 and a changing number to a NSMutableArray (so that it can be shown in a UITableView)?

For example, if the changing number at the moment is 8, then the array should contain: 1, 2, 3, 4, 5, 6, 7, 8. Thanks.

Jack Humphries
  • 13,056
  • 14
  • 84
  • 125
  • Why do you want to use an array for that? – Carl Norum Apr 07 '12 at 20:22
  • @CarlNorum I'm creating an app for my school newspaper, and need the array to allow people to choose a page number they want to flip to. The size of the newspaper is not always guaranteed, though, which is why I need this. – Jack Humphries Apr 07 '12 at 20:24
  • 2
    Have a look at http://stackoverflow.com/questions/8320987/looping-using-nsrange/8321037#8321037 – jscs Apr 07 '12 at 20:24
  • 1
    I understand why you want a table view with a list of numbers in it. I don't understand why you need an array for that. – Carl Norum Apr 07 '12 at 20:25
  • @JackHumphries look at lulius's comment.. this is the best approach I would say.. without using much memory. – Ankit Srivastava Apr 07 '12 at 20:33
  • @JackHumphries: you may have accepted a different answer, and the answer fits exactly your question, but to save memory & add performance, please consider my answer as well - you really dont need to make an array for this :) – Sebastian Flückiger Apr 08 '12 at 10:08
  • @SebastianFlückiger Thanks for your answer. I gave you an up vote :) – Jack Humphries Apr 08 '12 at 22:01

3 Answers3

4

i recommend the following approach (not needing an array). for your a numbers

-numberOfSectionsInTableView..{
    return 1;
}

-numberOfRowsInSection..{
    return a;
}

-cellForRowAtIndexPath..{
    UITableViewCell* cell = ...
    UILabel *label = ...
    [label setText:[NSString stringWithFormat:@"%d",indexPath.row+1]];
    [cell addSubView:label];
    return cell;
}

resulting in a table with 1 section, a rows, and each row will have a label with the number 1 to a on it.

sebastian

Sebastian Flückiger
  • 5,525
  • 8
  • 33
  • 69
2

Something like:

int number = 8;
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:number];
for (int i=1; i<=number; i++) {
    [mutableArray addObject:[NSString stringWithFormat:@"%i", i]]
}
NSLog(@"%@", [mutableArray description]);
Jack Humphries
  • 13,056
  • 14
  • 84
  • 125
phi
  • 10,634
  • 6
  • 53
  • 88
1

- (NSMutableArray*)arrayForNumber:(int)number {
    NSMutableArray* array = [NSMutableArray array];

    for (int i = 1; i <= number; i++) {
        [array addObject:[NSNumber numberWithInt:i]];
    }

    return array;
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270