开发者

Check existence of file on disk?

Currently I am loading data from a previous session into my application using the code below. To guard against there being no previous data I am using a temp variable to check the return value before making my assignment. I am just posting here as this feels a bit clunky, is there a way to check a file exists on disk so I can check before continuing, or is what I have the way to go?

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");

Prior to this I had (see below) but 开发者_如何学JAVAas you can imagine if NSKeyedUnarchiver did not find a file and returned "nil" it trashed my previously allocated array.

artistCollection = [[NSMutableArray alloc] init];
artistCollection = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/data"];

gary


Cocoa has a class that provides support for dealing with filesystem objects: NSFileManager. You can use a standard file manager (provided by +defaultManager) in conjunction with the -fileExistsAtPath: method, which returns a BOOL value for whether the file exists or not:

if([[NSFileManager defaultManager] fileExistsAtPath:@"/data"]) { /* ... */ }

Keep in mind this doesn't tell you anything about whether the file is accessible (permissions-wise), is a directory, etc. There are other NSFileManager functions for those.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜