0

我正在尝试将项目从“下载”移动到我的“垃圾箱”文件夹,但首先不删除它们。我在下面的实现中缺少什么,文件没有移动。


规格:

 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]);

我的输出中出现 Unable to move :(null) 。

文件确实在那里,所以我不确定问题仍然存在。

4

1 回答 1

2

您可以通过在 else 中记录错误来找出问题所在:

NSLog(@"Unable to move %@ %@", sourcepath, [error localizedDescription]);

此外,除非您在遇到错误时中止循环,否则您应该重置errornil.

此外,您可能应该使用NSWorkspaceperformFileOperation:NSWorkspaceRecycleOperation不是单独移动每个文件:

[[NSWorkspace sharedWorkspace] performFileOperation:NSWorkspaceRecycleOperation
                                             source:_downloadpath
                                        destination:@""
                                              files:list
                                                tag:nil];
于 2013-08-05T23:07:36.933 回答