I get an error when running my code. The culprit is me accessing a string from a plist below:
NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
NSLog(@"%@",sImageFile);
I have this in my cocos2d Init shown here:
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {
NSUserDefaults *sud = [NSUserDefaults standardUserDefaults];
NSString *ctlLang = [sud valueForKey:@"ctlLang"];
NSNumber *questionState = [sud valueForKey:@"questionState"];
NSNumber *scoreState = [sud valueForKey:@"scoreState"];
gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];
for (NSString *element in gameArray) {
NSLog(@"\nQL gameArray value=%d\n", [element intValue]);
}
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:ctlLang];
dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];
NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
NSLog(@"%@",sImageFile);
}
}
The printing of the string works fine in the init section of the scene. The problem occurs in a method I define later. For some reason it is not returning the string in the method shown here:
-(void) checkAnswer: (id) sender {
CGSize size = [[CCDirector sharedDirector] winSize];
CCMenuItemSprite *sAnswer = (CCMenuItemSprite *)sender;
NSLog(@"Checking Answer Tag is ---> %d",sAnswer.tag);
NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
NSLog(@"%@",sImageFile);
if ([question.answer integerValue] == sAnswer.tag) {
//...
}
}
What am I missing here? the program bombs at the NSLog statement.
You assign the object returned by
dictionaryWithContentsOfFile:to thedictionaryivar but you do not claim ownership of it by sending it aretainmessage to it:The method
dictionaryWithContentsOfFile:returns an object you do not own. Probably, by the timecheckAnswer:is executed the object has already been deallocated. You need to retain it:Or use
alloc-initWithContentsOfFile:instead, which returns an object you own:And the same goes for the
gameplayivar. You do not own the object returned byvalueForKey:and you need to retain it. So this line:should be: