2012-02-23 44 views
0

我有一個應用程序,每次應用程序啓動時都會使用保存的文件加載2條數據。運行得很好。在我的應用程序的新版本中,我想添加第三條數據。不過,我得到這個錯誤,當我運行它:將新數據添加到保存在iPhone上的現有已保存NSMutableArray中

終止應用程序由於未捕獲的異常 'NSRangeException',原因是:「* - [__ NSArrayM objectAtIndex:]:指數2超出範圍[0..1]

因爲當它在啓動時讀取文件時,當現有的已保存文件只包含兩個數據時,它會調用第三條數據。

這裏是我的代碼:

int roundingSegment = 1; 

然後:

- (void)viewDidLoad { 

//---Check for existence of the Archive File on Startup- 
NSFileManager *filemgr; 
NSString *docsDir; 
NSArray *dirPaths; 
filemgr = [NSFileManager defaultManager]; 

// Get the documents directory 
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
docsDir = [dirPaths objectAtIndex:0]; 

// Build the path to the data file 
dataFilePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"data.archive"]]; 

// Check if the file already exists, and if so, loads the data 
if ([filemgr fileExistsAtPath:dataFilePath]) { 
    NSMutableArray *dataArray; 
    dataArray = [NSKeyedUnarchiver unarchiveObjectWithFile:dataFilePath]; 
    defaultValueTextField.text = [dataArray objectAtIndex:0]; 
    segment = [[dataArray objectAtIndex:1] intValue]; 
     roundingSegment = [[dataArray objectAtIndex:2] intValue]; 
    NSLog(@" Segment is %d", segment); 
     NSLog(@" RoundingSegment is %d", roundingSegment); 
    } 

[super viewDidLoad]; 
} 

在方法到底對不對出現問題的原因有兩個數據片的現有NSMutableArray的文件已經存在,我的代碼正試圖讀取第三個,即'roundingSegment'變量。 (我在哪裏縮進代碼//檢查文件是否存在...)

我是否必須刪除現有的NSMutableArray用戶在加載NEW版本的應用程序時保存了他的數據?如果是這樣,怎麼樣?

或者,更好的辦法是在應用程序的第一次運行中增加和添加第三塊數據,以便在它試圖獲取我的'roundingSegment'變量時不會掛起?

任何幫助你可以借出將不勝感激!

回答

0

您需要檢查[dataArray count]以查看陣列中有多少個元素。

您還應該考慮重構代碼以使用更好的機制來存儲應用程序數據。看看NSUserDefaults