【问题标题】:Check if file name exists in document directory检查文档目录中是否存在文件名
【发布时间】:2011-09-23 09:26:27
【问题描述】:

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

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

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

【问题讨论】:

    标签: iphone objective-c cocoa-touch


    【解决方案1】:

    使用NSFileManagerfileExistsAtPath:方法检查是否存在。

    用法

    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 */
    }
    

    【讨论】:

      【解决方案2】:
      if ([[NSFileManager defaultManager] fileExistsAtPath:myFilePath])
      

      【讨论】:

        【解决方案3】:
        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
        }
        

        【讨论】:

          【解决方案4】:

          正如 Apple 文档所说,最好执行一些操作然后处理不存在的文件,而不是检查文件是否存在。

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-07-15
            • 2023-03-26
            • 2013-08-02
            • 2013-04-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多