gpt4 book ai didi

iphone - 从文件读取数据时出现“NSRangeException”

转载 作者:行者123 更新时间:2023-12-03 17:13:38 24 4
gpt4 key购买 nike

我试图在按下主页按钮时保存数据。这是我的相关代码。

   - (NSString *) saveFilePath
{
NSArray *path =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[path objectAtIndex:0] stringByAppendingPathComponent:@"savefile.plist"];

}
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSArray *values = [[NSArray alloc] initWithObjects:
[NSNumber numberWithInt:askedQuestions], //for questionLabel
[NSNumber numberWithInt:timeMin], //timeMin
[NSNumber numberWithInt:timeSec], //timeSec
[NSNumber numberWithInt:skipCount], //skipped question
[NSNumber numberWithInt:correctAnswers], //corectAnswers
nil];
[values writeToFile:[self saveFilePath] atomically:YES];
}

saveFilePath 方法提供文件路径。

并在viewDidLoad中

NSString *myPath = [self saveFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists)
{
NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
_readerLabel.text = [[values objectAtIndex:0] stringValue];
askedQuestions=[[values objectAtIndex:0] intValue];
timeMin=[[values objectAtIndex:1]intValue];
timeSec=[[values objectAtIndex:2]intValue];
skipCount=[[values objectAtIndex:3]intValue];
correctAnswers=[[values objectAtIndex:4]intValue];

}

UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:myApp];

我得到了这个:

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]:        index (0) beyond bounds (0)'
*** First throw call stack:
(0x16a1012 0x13aee7e 0x16a0deb 0x16957e0 0x6891 0x312d 0x305817 0x305882 0x254a25 0x254dbf 0x254f55 0x25df67 0x221fcc 0x222fab 0x234315 0x23524b 0x226cf8 0x2703df9 0x2703ad0 0x1616bf5 0x1616962 0x1647bb6 0x1646f44 0x1646e1b 0x2227da 0x22465c 0x26cd 0x25f5)
libc++abi.dylib: terminate called throwing an exception

代码哪里出了问题。请帮忙!

最佳答案

您没有检查是否有任何效果!

如果会发生什么

NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];

要么失败(文件可能不存在),要么返回一个包含 0 个项目的数组?

您需要添加类似以下内容:

NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
if (values.count > 0) {
...
}

您还应该在 applicationDidEnterBackground: 上设置一个断点,并逐步执行以确保您的保存方法按预期工作。

<小时/>

另外,我怀疑这两行之一是错误的:

_readerLabel.text = [[values objectAtIndex:0] stringValue];
askedQuestions=[[values objectAtIndex:0] intValue];

他们都在请求索引 0 处的项目

关于iphone - 从文件读取数据时出现“NSRangeException”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13494685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com