2012-11-21 23 views
1

我試圖按住home按鈕時保存數據。 這是我的相關代碼。從文件讀取數據時出現'NSRangeException'

- (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 

哪裏是在代碼中的問題。請幫忙!

回答

1

你不檢查是否有任何工作!

會發生什麼,如果

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

要麼失敗(該文件可能不存在),或者如果它返回一個空的數組?

您需要添加類似:

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

您還應該設置一個斷點applicationDidEnterBackground:和步驟雖然以確保您的保存方法您正常工作。


而且,我懷疑這兩條線中的一個是錯誤的:

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

他們都要求該項目在索引0

+0

感謝您的即時幫助。如果我只使用objectAtIndex = 0,從索引1開始向前崩潰,代碼就會正確。 –

+0

然後我猜你的文件返回的數組只包含一個對象:) – deanWombourne

+0

我刪除了創建的文件,現在一切都正常。 @dean感謝您的幫助。 –

相關問題