目前,我正在使用下面的代码将上一个 session 的数据加载到我的应用程序中。为了防止没有以前的数据,我在进行分配之前使用临时变量来检查返回值。我只是在这里发帖,因为这感觉有点笨拙,有没有办法检查磁盘上是否存在文件,以便我可以在继续之前进行检查,或者我有什么办法吗?
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");
在此之前我已经(见下文),但正如你可以想象的,如果 NSKeyedUnarchiver 没有找到文件并返回“nil”,它会破坏我之前分配的数组。
artistCollection = [[NSMutableArray alloc] init];
artistCollection = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/data"];
加里
最佳答案
Cocoa 有一个类,为处理文件系统对象提供支持: NSFileManager 。您可以将标准文件管理器(由 +defaultManager
提供)与 -fileExistsAtPath:
方法结合使用,该方法返回一个 BOOL
值来指示是否文件是否存在:
if([[NSFileManager defaultManager] fileExistsAtPath:@"/data"]) { /* ... */ }
请记住,这不会告诉您有关该文件是否可访问(权限方面)、是否是一个目录等的任何信息。还有其他 NSFileManager 函数用于这些。
关于objective-c - 检查磁盘上文件是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1651578/