[英]Rename the folder of document directory
這可能很容易,但我沒有遇到問題。
我正在使用下面的代碼來重命名文檔目錄的文件夾,並且除一種情況外工作正常。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Photos"];
NSArray * arrAllItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:NULL]; // List of all items
NSString *filePath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [arrAllItems objectAtIndex:tagSelected]]];
NSString *newDirectoryName = txtAlbumName.text; // Name entered by user
NSString *oldPath = filePath;
NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newDirectoryName];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error];
if (error) {
NSLog(@"%@",error.localizedDescription);
// handle error
}
現在,我的問題是,如果there is a folder named "A"(capital letter A) and I am renaming it to "a" (small letter a), then it is not working and giving an error.
我不明白問題出在哪里。
HFS+ 文件系統(在 OS X 上)不區分大小寫,但保留大小寫。 這意味着如果您創建一個文件夾“A”,然后檢查是否有文件夾“a”,您將得到“是”作為答案。
文件管理器moveItemAtPath:toPath:...
首先檢查目標路徑是否已經存在,因此失敗
NSUnderlyingError=0x7126dc0 "The operation couldn’t be completed. File exists"
一種解決方法是首先將目錄重命名為一些完全不同的名稱:
A --> temporary name --> a
但是一個更簡單的解決方案是使用 BSD rename()
系統調用,因為它可以毫無問題地將“A”重命名為“a”:
if (rename([oldPath fileSystemRepresentation], [newPath fileSystemRepresentation]) == -1) {
NSLog(@"%s",strerror(errno));
}
請注意,該問題僅發生在 iOS 模擬器上,而不發生在設備上,因為設備文件系統區分大小寫。
迅速:
let result = oldURL.withUnsafeFileSystemRepresentation { oldPath in
newURL.withUnsafeFileSystemRepresentation { newPath in
rename(oldPath, newPath)
}
}
if result != 0 {
NSLog("%s", strerror(errno))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.