2012-08-30 61 views
1

如果存在具有相同名稱的文件,則在objective-c中重命名文件的最佳方法是什麼。如果文件已存在,則重命名文件

理想情況下,如果名爲untitled.png的文件已存在,我想將untitled.png命名爲untitled-1.png。

我已經在下面列出了我的解決方案作爲答案,但我認爲應該有一個更好的方法(內置函數)來做到這一點。

我的解決方案不是線程安全的,並且容易受到競爭條件的影響。

回答

5

下面的函數返回下一個可用的文件名:

//returns next available unique filename (with suffix appended) 
- (NSString*) getNextAvailableFileName:(NSString*)filePath suffix:(NSString*)suffix 
{ 

    NSFileManager* fm = [NSFileManager defaultManager]; 

    if ([fm fileExistsAtPath:[NSString stringWithFormat:@"%@.%@",filePath,suffix]]) { 
     int maxIterations = 999; 
     for (int numDuplicates = 1; numDuplicates < maxIterations; numDuplicates++) 
     { 
      NSString* testPath = [NSString stringWithFormat:@"%@-%d.%@",filePath,numDuplicates,suffix]; 
      if (![fm fileExistsAtPath:testPath]) 
      { 
       return testPath; 
      } 
     } 
    } 

    return [NSString stringWithFormat:@"%@.%@",filePath,suffix]; 
} 

調用函數的例子如下:

//See" http://stackoverflow.com/questions/1269214/how-to-save-an-image-that-is-returned-by-uiimagepickerview-controller 

    // Get the image from the result 
    UIImage* image = [info valueForKey:@"UIImagePickerControllerOriginalImage"]; 

    // Get the data for the image as a PNG 
    NSData* imageData = UIImagePNGRepresentation(image); 

    // Give a name to the file 
    NSString* imageName = @"image"; 
    NSString* suffix = @"png"; 


    // Now we get the full path to the file 
    NSString* filePath = [currentDirectory stringByAppendingPathComponent:imageName]; 

    //If file already exists, append unique suffix to file name 
    NSString* fullPathToFile = [self getNextAvailableFileName:filePath suffix:suffix]; 

    // and then we write it out 
    [imageData writeToFile:fullPathToFile atomically:NO]; 
相關問題