Instance NSMutableArray not keeping values after method exit

Sunday, May 4, 2014

I started learning objective-c a few days ago, and while making a simple Mastermind application to practice I ran into a problem that I can't seem to solve, even with the help of Google :(


I am using an instance variable NSMutableArray named colArray to stock 4 colors that are randomly selected in a "newGame" method at the beginning of the game. The issue is that after leaving "newGame", colArray loses the items it contained, resulting in a 'nil' array.


I tried initializing the array in viewDidLoad with color values, but it only kept the original values, even after they were changed in newGame, so I guess the issue is in newGame, and that it is somehow not 'really' affecting the array, but if it is the case I don't understand why.


Surely this must be a simple problem, but I've been looking for a while now and I can't seem to spot it :/ Here is the related code :


newGame



- (IBAction)newGame:(id)sender {
NSLog(@"Randomly setting colArray");
colArray = [[NSMutableArray alloc] init];
for (int i=0; i<4; i++) {
int rdm = arc4random()%7 + 1;
switch (rdm) {
case 1:
[colArray setObject:red atIndexedSubscript:i];
NSLog(@"Red");
break;
case 2:
[colArray setObject:blue atIndexedSubscript:i];
NSLog(@"Blue");
break;
case 3:
[colArray setObject:green atIndexedSubscript:i];
NSLog(@"Green");
break;
case 4:
[colArray setObject:yellow atIndexedSubscript:i];
NSLog(@"Yellow");
break;
case 5:
[colArray setObject:orange atIndexedSubscript:i];
NSLog(@"Orange");
break;
case 6:
[colArray setObject:black atIndexedSubscript:i];
NSLog(@"Black");
break;
default:
[colArray setObject:silver atIndexedSubscript:i];
NSLog(@"Silver");
break;
}
}
}


Instance Variables in ViewController.h



@interface ViewController : UIViewController
{
NSMutableArray *sqArray, *colArray;
UIColor *red, *blue, *green, *yellow, *orange, *black, *silver, *emptyCol;
NSMutableDictionary *btnDic;

int cptSq;
int cptAttempt;
}


Validate method (where colArray is nil)



- (IBAction)validate:(id)sender {
[...]

if (nbEmpty == 0)
{
int nbPerfect = 0;
int nbMoyen = 0;

for (int i=1; i<5; i++)
{
NSString *btnName = [NSString stringWithFormat:@"a%dsq%d", cptAttempt, i];
UIColor *sqColor = [[btnDic objectForKey:btnName] backgroundColor];
UIColor *correctColor = [colArray objectAtIndex:(i-1)];
if ([sqColor isEqual: correctColor])
{
nbPerfect++;
}
else
{
for (int x=1; x < 5; x++)
{
if ([sqColor isEqual: [colArray objectAtIndex:(x-1)]])
{
nbMoyen++;
x = 6;
}
}
}
}
}
}
@end






http://ift.tt/1lQ5kkQ