Search code examples
iphoneiosios4nsarray

Incrementing NSArray on button click


I'm reading a text file line by line, and storing it into a NSArray. What I want to achieve is to increment the index of my NSArray when the user clicks a button.

Code:

 text.editable = NO;
 NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"firstyea" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil]; // reads file into memory as an NSString
 NSArray *lines = [fileString componentsSeparatedByString:@"\n"]; // each line, adjust character for line endings
 NSString *wat = [lines objectAtIndex:1]; 
 text.text = wat;
 [self.view addSubview:text];

So I have to increment objectAtIndex by 1 whenever the user clicks a button. I can do it in C++ by having a variable of type int, and saying something like objectAtIndex:counter++ but I don't know how to do the same thing in IOS.


Solution

  • You can't do it with NSArray, you need to use a NSMutableArray You should take a variable of type static int.

    For example:

    static int counter=0; //define it globally
    
    NSMutableArray *tempArray=[[NSMutableArray alloc] init];
    
    [tempArray insertObject:@"Your Data From File" atIndex:counter++];
    

    Note: Don't forget to release the array after you're finished using it!