运行代码时出错。罪魁祸首是我从下面的一个plist访问一个字符串:
NSString *sImageFile = [dictionary objectForKey:@"answerCorrect"];
NSLog(@"%@",sImageFile);
我在这里显示的cocos2d Init中有这个:
-(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);
}
}
字符串的打印在场景的init部分中正常工作。问题出现在我稍后定义的方法中。由于某种原因,它不会在此处显示的方法中返回字符串:
-(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) {
//...
}
}
我在这里缺少什么?该计划在NSLog声明中爆炸。
答案 0 :(得分:5)
您将dictionaryWithContentsOfFile:
返回的对象分配给dictionary
ivar,但您不会通过向其发送retain
消息来声明对其的所有权:
dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];
方法dictionaryWithContentsOfFile:
会返回您不拥有的对象。可能在执行checkAnswer:
时,对象已被释放。你需要保留它:
dictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
或者改为使用alloc-initWithContentsOfFile:
,它会返回一个你拥有的对象:
dictionary = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
同样适用于gameplay
ivar。您不拥有 valueForKey:
返回的对象,您需要保留它。所以这一行:
gameArray = (NSMutableArray *)[sud valueForKey:@"gameArray"];
应该是:
gameArray = [[sud valueForKey:@"gameArray"] retain];
答案 1 :(得分:0)
我认为您不会保留在init方法中创建的自动释放字典。您将字典设置为ivar但不保留它。当您稍后访问它时,它可能不再有效