I'm performing some basic operations on two mutable arrays. However, the program behaves strangely. The second array resets itself after a function ends.
First, I allocate memory for the two arrays. I then populate originalArray
with numbers from 0..10.
My code looks like this.
ViewController.h
@property (nonatomic, strong) NSMutableArray *originalArray;
@property (nonatomic, strong) NSMutableArray *secondArray;
ViewController.c
static int level=1;
- (void)viewDidLoad
{
[super viewDidLoad];
[self firstArrayInit];
[self secondArrayInit];
[self startDisplaying];
}
-(void) firstArrayInit{
self.originalArray = [NSMutableArray array];
for (int i=0; i<10; i++) {
[self.originalArray addObject:[NSNumber numberWithInteger:i]];
}
}
-(void)secondArrayInit{
self.secondArray = [[NSMutableArray alloc]init];
}
-(void) startDisplaying{
NSLog(@"Initial Array is %@", self.originalArray);
self.mytimer = [NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:@selector(displayNumber)
userInfo:nil
repeats:YES];
NSLog(@"SecondA: %@", self.secondArray); //prints EMPTY ARRAY!!
}
-(void) displayNumber{
static int num=0;
NSLog(@"Num: %d", num);
NSLog(@"Level: %d", level);
if (num < level){
//display on a label
myLabel.text = [NSString stringWithFormat:@"%@", [self.originalArray objectAtIndex:num]];
[self addToSecondArray:num];
num++;
NSLog(@"SecondA: %@", self.secondArray); //prints the contents of Array FINE!!
}
else{
NSLog(@"SecondA2: %@", self.secondArray); //PRINTS EMPTY ARRAY!!
}
}
-(void)addToSecondArray:(int)myNumber{
[self.secondArray addObject:[self.originalArray objectAtIndex:myNumber]];
}
Outputs:
Initial Array is (
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
)
Num: 0
Level: 1
SecondA: (
0
)
Num:1
Level: 1
SecondA2: (
)