我在运行代码时遇到错误。罪魁祸首是我从下面的 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);
}
}
字符串的打印在场景的初始部分工作正常。问题出现在我后面定义的一个方法中。由于某种原因,它没有在此处显示的方法中返回字符串:
-(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 语句中爆炸。
最佳答案
您将 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];
关于iphone - 发送到实例的选择器无效 - objectForKey :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7100887/