Noitidart Noitidart - 4 months ago 14
Objective-C Question

recycleURLs:completionHandler: with NIL makes it block until completion?

I was sending a file to the trash with

[NSWorkSpace recycleURLs: myArrayOfOneNsurl
completionHandler: NIL]


myArrayOfOneNsurl
is a
NSArray
created with
arrayWithObject:
of a single
NSURL
that was created for an absolute file path with
fileURLWithPath:isDirectory:
.

The normal way to tell if it is successful is to use the
completionHandler
and then check if the 2nd arg (
NSError
) is
NIL
, which means success.

Is there anyway to check success without this callback? Currently I have setup a loop after calling this, to check for file existence, if 1second has past and it still exists, I declare fail. I was wondering if I set
NIL
as second arg to
recycleURLs:completionHandler:
does it make it block until the process completes (regardless of success)? In my tests, the very first check always finds that the file is no longer at its original place (meaning it was trashed), but I'm not sure if my computer is just super fast, or it really is blocking until file operation completes.

Answer

This API is async. Passing NULL as completionHandler only means, that you are not interested in result. The only way to know when operation finished and was it successful is using completionHandler.

If you really need to make it sync, you may use following approach (although I don't recommend that):

__block BOOL recycleFinished = NO;
__block NSError *recycleError = nil;
[[NSWorkspace sharedWorkspace] recycleURLs:myArrayOfOneNsurl
                         completionHandler:^(NSDictionary<NSURL *,NSURL *> * _Nonnull newURLs, NSError * _Nullable error) {
    recycleFinished = YES;
    recycleError = error;
}];

while (!recycleFinished) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.5]];
}

// access recycleError
NSLog(@"%@", recycleError);