所以我试图将数组保存到文件中。这应该在以下代码中完成,但通过调用该 addProjectsObject
方法,程序会崩溃并出现以下错误代码:
***** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteData count]: unrecognized selector sent to instance 0x7eeb800'**
我发布了我认为与问题相关的代码,我还需要提到在同一个filePath中存储了另一个文件,它运行良好。我突然想到路径可能是问题,但是由于两个文件的名称不同,这不应该是问题吗?
-(void) addProjectsObject:(NSString *)newProject{
projects = [self getProjectsFromDisk];
[projects addObject:newProject];
[self saveProjectsToDisk];
}
-(NSMutableArray *) getProjectsFromDisk{
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"projects";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if(![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath])
{
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];}
NSMutableArray* temp = [[NSMutableArray alloc]initWithArray:[NSData dataWithContentsOfFile:fileAtPath]];
return temp;
}
-(void) saveProjectsToDisk {
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"projects";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if(![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath])
{
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];}
[projects writeToFile:fileAtPath atomically:NO];
}