考虑以下两种从文件中读取字符串的方法:
NSString *path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"txt"];
NSString *string = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:NULL];
NSString *path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"txt"];
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:path];
NSData *data = [file readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[file closeFile];
我更愿意依赖方法#1,但在以下上下文中使用时它的行为很奇怪:
NSString *string; // CLASS VARIABLE
(void) setupView
{
string = ...; // LOADING THE STRING
}
(void) drawView
{
...; // USING THE STRING
}
简而言之,它是一个基于 NSTimer 的 OpenGL-ES 绘图循环。问题是字符串只能在第一帧访问。在下一帧,iPhone 模拟器 (2.2) 在尝试访问字符串时崩溃。
可能有人会说“我的代码或我正在使用的 OpenGL-ES 代码中的某些东西”......但是如何解释一个奇怪的事实,即如果我使用方法 #2 加载字符串,一切都按预期工作?
有什么线索吗?