removeItemAtPath completion

2020-05-06 10:33发布

问题:

I am deleting a file at a path in this way:

UIPanGestureRecognizer *gesture = (UIPanGestureRecognizer *)sender;
UIButton *button = (UIButton *)gesture.view;
[[(UIPanGestureRecognizer*)sender view] removeFromSuperview];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *myFilePath = [documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", button.titleLabel.text]];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:myFilePath error:NULL];
[self ReloadBusinessCards];

then I am calling the method [self ReloadBusinessCards]; which reloads the files. The problem is that it happens that deleting the file takes a long time (0.5 sec.) and the method is called before. I would like to prevent this, but i don't think it would be a good idea to set an NSTimer of 1 sec. for example because if the app runs slower the file could be deleted after more. Is there a method that notifies you when the file is deleted?

回答1:

Wrap the delete method in an if() statement. -removeItemAtPath: returns a BOOL so you can check to see if it's YES or NO.

if ([fileManager removeItemAtPath:myFilePath error:NULL]) {
    [self ReloadBusinessCards];
}


回答2:

You can wait until the operation is complete using

[receiver performSelectorOnMainThread:@selector(sel) withObject:nil waitUntilDone:NO]

or use the GCD with a completion handler to verify that the process of erase is actually done