Iphone 检查文档目录中是否存在文件名

Iphone 检查文档目录中是否存在文件名,iphone,objective-c,cocoa-touch,Iphone,Objective C,Cocoa Touch,在我的应用程序中,我使用以下代码将图像/文件保存到应用程序的文档目录中: -(void)saveImageDetailsToAppBundle{ NSData *imageData = UIImagePNGRepresentation(userSavedImage); //convert image into .png format. NSFileManager *fileManager = [NSFileManager defaultManager];//create inst

在我的应用程序中,我使用以下代码将图像/文件保存到应用程序的文档目录中:

-(void)saveImageDetailsToAppBundle{
    NSData *imageData = UIImagePNGRepresentation(userSavedImage); //convert image into .png format.
    NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
    NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",txtImageName.text]]; //add our image to the path

    NSLog(fullPath);

    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image

    NSLog(@"image saved"); 
}

但是,图像名称存在问题。如果文档目录中存在文件,则同名的新文件将覆盖旧文件。如何检查文档目录中是否存在文件名?

使用
NSFileManager
的方法检查文件名是否存在

使用
正如苹果的文档所说,执行一些操作然后处理不存在文件比检查文件是否存在更好

注意:不建议尝试根据文件系统的当前状态或文件系统上的特定文件来判断行为。这样做可能会导致奇怪的行为或种族状况。尝试一项操作(如加载文件或创建目录)、检查错误并优雅地处理这些错误,要比提前判断操作是否会成功要好得多。有关文件系统竞争条件的更多信息,请参阅《安全编码指南》中的“竞争条件和安全文件操作”

if ( ![fileManager fileExistsAtPath:filePath] ) {
    /* File doesn't exist. Save the image at the path */
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; 
} else {
    /* File exists at path. Resolve and save */
}
if ([[NSFileManager defaultManager] fileExistsAtPath:myFilePath])
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"file name"];

if([fileManager fileExistsAtPath:writablePath]){ 
// file exist
}
else{ 
    // file doesn't exist
}