检查磁盘上是否存在文件?

fuz*_*oat 1 cocoa objective-c

目前,我正在使用以下代码将先前会话中的数据加载到我的应用程序中.为了防止没有先前的数据,我在使用临时变量来检查返回值,然后再进行分配.我只是发布在这里,因为这感觉有点笨重,有没有办法检查磁盘上存在的文件,所以我可以在继续之前检查,或者我有什么方法去?

NSMutableArray *artistCollection;
NSMutableArray *artistCollection_LOAD;

artistCollection = [[NSMutableArray alloc] init];
artistCollection_LOAD = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/data"];
if(artistCollection_LOAD != nil) artistCollection = artistCollection_LOAD;
else NSLog(@"(*) - Saved Data Not Found");
Run Code Online (Sandbox Code Playgroud)

在此之前,我(见下文),但你可以想象如果NSKeyedUnarchiver没有找到一个文件并返回"nil",它会破坏我以前分配的数组.

artistCollection = [[NSMutableArray alloc] init];
artistCollection = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/data"];
Run Code Online (Sandbox Code Playgroud)

加里

Tim*_*Tim 12

Cocoa有一个类,它为处理文件系统对象提供支持:NSFileManager.您可以将标准文件管理器(由提供者+defaultManager)与该-fileExistsAtPath:方法结合使用,该方法返回BOOL文件是否存在的值:

if([[NSFileManager defaultManager] fileExistsAtPath:@"/data"]) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

请记住,这并不能告诉您文件是否可访问(权限方面),目录等等.还有其他NSFileManager函数.