【发布时间】:2016-01-18 04:05:03
【问题描述】:
我正在尝试使用 NSFileManager 将文件从 Documents/Inbox 文件夹移动到 Documents 文件夹。我使用断点来找出我的代码没有工作的地方,一切似乎都运行良好,直到它到达实际移动文件的部分。找到了目录并在调试器中记录了文件,但它不会移动。这是我的整个 viewDidLoad 方法([super viewDidLoad]; 中什么都没有):
//Turn every file inside the directory into an array
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appFolderPath = [path objectAtIndex:0];
NSString *inboxAppFolderPath = [appFolderPath stringByAppendingString:@"/Inbox"]; //changes the directory address to make it for the inbox
//NSPredicates to filter out files I don't want in my NSArray
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not SELF beginswith[c] '.DS_Store'"];
NSPredicate *inboxPredicate = [NSPredicate predicateWithFormat:@"not SELF beginswith[c] 'Inbox'"];
recipes = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:appFolderPath error:nil];
recipes = [recipes filteredArrayUsingPredicate:predicate];
recipes = [recipes filteredArrayUsingPredicate:inboxPredicate];
//get to inbox directory
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:inboxAppFolderPath,documentsDirectory] error:nil];
//move all the files over
for (int i = 0; i != [inboxContents count]; i++)
{
NSString *oldPath = [NSString stringWithFormat:inboxAppFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
NSString *newPath = [NSString stringWithFormat:appFolderPath, documentsDirectory, [inboxContents objectAtIndex:i]];
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
}
【问题讨论】:
-
看两件事:moveItemAtPath 返回一个布尔值,你检查过它的返回值吗?另外,您是否尝试过传入一个 NSError 对象(而不是 nil)来查看可能发生的错误?
-
我添加了一个NSError,并将移动文件的代码更改为
BOOL success = [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];,然后添加了一个if语句来检查错误。我收到错误“删除路径处的文件时出错:(null)”,就是这样。 -
您能否在
moveItemAtPath调用之前立即对oldPath和newPath的值进行NSLog 并在问题中添加一些示例?有时它有助于准确了解我们正在处理的内容。 -
@Thunk oldPath =
/Users/Justin/Library/Developer/CoreSimulator/Devices/4308BE72-79FB-4237-8BB8-7F1E513464C1/data/Containers/Data/Application/099DC9F2-0EF4-4FC2-8FAC-37C14173A350/Documents/Inbox和 newPath =/Users/Justin/Library/Developer/CoreSimulator/Devices/4308BE72-79FB-4237-8BB8-7F1E513464C1/data/Containers/Data/Application/099DC9F2-0EF4-4FC2-8FAC-37C14173A350/Documents
标签: ios objective-c nsfilemanager