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結果是完整的。
/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
但是當已經存在的文件夾。
結果是失敗。
2012-10-04 06:48:31.488 tempPrg[1243:11303] Copy Failed
2012-10-04 06:48:31.497 tempPrg[1243:11303] Copy Failed