我正试图将下载中的项目移动到我的垃圾桶文件夹中,而不是先删除它们。我在下面的实现中缺少的是,文件没有移动。
规格:
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)。
文件确实在那里,所以我不确定问题还在哪里。
您可以通过在else:中记录错误来找出问题所在
NSLog(@"Unable to move %@ %@", sourcepath, [error localizedDescription]);
此外,除非遇到错误时中止循环,否则应将error
重置为nil
。
此外,您可能应该使用NSWorkspace
和performFileOperation:NSWorkspaceRecycleOperation
,而不是单独移动每个文件:
[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation
source:_downloadpath
destination:@""
files:list
tag:nil];