我正在尝试将项目从“下载”移动到“我的垃圾箱”文件夹,而不是先删除它们。我在下面的实现中遗漏了什么,文件没有被移动。
具体细节:
NSString *trashpath=[NSHomeDirectory() stringByAppendingPathComponent:@".Trash"];
NSString *downloadpath=[NSHomeDirectory() stringByAppendingPathComponent:@"Downloads"];
- (void) moveToTrash{
NSError * error = nil;
NSArray * list = [_filemanager contentsOfDirectoryAtPath:_downloadpath error:&error];
//Move items to the trash
for(id obj in list){
NSString *sourcepath = [_downloadpath stringByAppendingPathComponent:obj];
NSString *destpath= [_trashpath stringByAppendingPathComponent:obj];
if([_filemanager moveItemAtPath:sourcepath toPath:destpath error:&error] == YES)
NSLog(@"Moved to trash :%@ ",destpath);
else
NSLog(@"Unable to move %@ ",sourcepath);
}
}
我尝试使用BergQuester建议的以下代码
if([[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation source:_downloadpath
destination:@"" files:list tag:nil] == YES)
NSLog(@"Moved to Trash");
else
NSLog(@"Unable to move :%@",[error localizedFailureReason]);
我的输出中无法移动:( null)。
文件确实存在,所以我不确定问题是什么。
答案 0 :(得分:2)
您可以通过在其他地方记录错误来找出问题所在:
NSLog(@"Unable to move %@ %@", sourcepath, [error localizedDescription]);
此外,除非您在遇到错误时中止循环,否则应将error
重置为nil
。
此外,您应该使用NSWorkspace
和performFileOperation:NSWorkspaceRecycleOperation
而不是单独移动每个文件:
[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation
source:_downloadpath
destination:@""
files:list
tag:nil];