Noitidart
Noitidart

Reputation: 37298

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.

Upvotes: 1

Views: 292

Answers (2)

Dyami Caliri
Dyami Caliri

Reputation: 61

For trashing a single file or directory, you can use NSFileManager trashItemAtURL instead. It is synchronous, so you avoid the headaches with the completion callback.

NSError * error = nil;
[[NSFileManager defaultManager] trashItemAtURL:url resultingItemURL:nil error:&error];

Upvotes: 3

Borys Verebskyi
Borys Verebskyi

Reputation: 4278

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

Upvotes: 1

Related Questions