2012-10-03 33 views
2

對於使用NSFileManager的「copyItemAtPath」方法,如果存在相同的文件或文件夾,則會發生錯誤。如何使用NSFileManager替換文件或文件夾?

NSFileManager中是否有替換功能?

(如果存在相同的文件,刪除和複製如果沒有,只是複製。)

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    [self generateTableContents]; 

} 


- (void)generateTableContents { 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSArray *appsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentPath = [appsDirectory objectAtIndex:0]; 

    [fileManager changeCurrentDirectoryPath:documentPath]; 
    [fileManager createDirectoryAtPath:@"user_List1" withIntermediateDirectories:YES attributes:nil error:nil]; 

    NSString *bundlePath = [[NSBundle mainBundle] resourcePath]; 

    NSError *error; // to hold the error details if things go wrong 
    NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"IMG_0523" ofType:@"JPG"]; 

    if ([fileManager copyItemAtPath:sourcePath toPath: @"./user_List1/newIMG_0523.JPG" error:&error]) { 
     NSLog(@"Copy complete!"); 
    } else { 
     NSLog(@"Copy Failed : %@", error); 
    } 


    if ([fileManager copyItemAtPath:@"./user_List1" toPath: @"./user_List2" error:&error]) { 
     NSLog(@"Copy complete!"); 
    } else { 
     NSLog(@"Copy Failed : %@", error); 
    } 



} 

Excuted結果是完整的。

enter image description here

/Users/nice7285/Library/Caches/appCode10/DerivedData/tempPrg-dd15264d/Build/Products/Debug-iphonesimulator/tempPrg.app/tempPrg 
Simulator session started with process 1184 
2012-10-04 06:28:32.653 tempPrg[1184:11303] Copy complete! 
2012-10-04 06:28:32.672 tempPrg[1184:11303] Copy complete! 

Process finished with exit code 143 

但是當已經存在的文件夾。

enter image description here

結果是失敗。

2012-10-04 06:48:31.488 tempPrg[1243:11303] Copy Failed 
2012-10-04 06:48:31.497 tempPrg[1243:11303] Copy Failed 

回答

6

你需要做一個原子保存,例如:

NSData *myData = ...; //fetched from somewhere 
[myData writeToFile:targetPath atomically:YES]; 

但由於您使用的copyItemAtPath,我不知道,如果原子與它的工作原理,所以我只想去的快骯髒的黑客:

if ([fileManager fileExistsAtPath:txtPath] == YES) { 
    [fileManager removeItemAtPath:txtPath error:&error] 
} 

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"]; 
[fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error]; 

來源:IOS: copy a file in documents folder

相關問題