向iPhone上保存的现有NSMutableArray添加新数据
我有一个应用程序,每次应用程序启动时都使用保存的文件加载2条数据。运行非常好。在我的应用程序的新版本中,我想添加第三条数据。但是,当我运行它时,会出现以下错误: 由于未捕获异常“NSRangeException”而终止应用程序,原因:'*-[\uu NSArrayM objectAtIndex:]:索引2超出边界[0..1] 因为当它在启动时读取文件时,当现有保存的文件仅包含两条数据时,它会调用第三条数据 这是我的密码:向iPhone上保存的现有NSMutableArray添加新数据,iphone,objective-c,xcode,Iphone,Objective C,Xcode,我有一个应用程序,每次应用程序启动时都使用保存的文件加载2条数据。运行非常好。在我的应用程序的新版本中,我想添加第三条数据。但是,当我运行它时,会出现以下错误: 由于未捕获异常“NSRangeException”而终止应用程序,原因:'*-[\uu NSArrayM objectAtIndex:]:索引2超出边界[0..1] 因为当它在启动时读取文件时,当现有保存的文件仅包含两条数据时,它会调用第三条数据 这是我的密码: int roundingSegment = 1; 然后: - (void
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?如果是,怎么办
或者,更可取的是,是否有一种方法可以在应用程序的第一次运行时增加和添加第三条数据,以便在尝试获取我的“roundingSegment”变量时不会挂起
如果您能提供任何帮助,我们将不胜感激 您需要检查[dataArray count]以查看数组中有多少个元素
您还应该考虑重构代码以使用更好的机制来存储应用程序数据。查看
NSUserDefaults