【发布时间】:2012-05-16 08:21:29
【问题描述】:
所以我尝试将数组保存到文件中。这应该在以下代码中完成,但通过调用 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];
}
【问题讨论】:
-
您是否尝试过调试应用程序崩溃的确切时间?
-
正如 Saad 所说,问题似乎出在这一行: NSMutableArray* temp = [[NSMutableArray alloc]initWithArray:[NSData dataWithContentsOfFile:fileAtPath]];我似乎错过了一些关于数据类型的东西,但我完全不知道它可能是什么
标签: iphone objective-c xcode nsmutablearray nsfilemanager