Remove directory if empty

ios, nsfilemanager, objective-c

Solution

You want this:

NSError *error = nil;
NSArray *folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:theDirectory error:&error];
if (folderContents) {
    if (folderContents.count == 0) {
        NSLog(@"empty");
        [[NSFileManager defaultManager] removeItemAtPath:theDirectory error:&error];
    }
} else {
    // log error
}

Problem

I'm trying to check if a folder is empty and if so remove it, using the following code: ``` NSArray *folderContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:theDirectory error:&error]; if (!folderContents){ if (folderContents.count == 0) { NSLog(@"empty"); [[NSFileManager defaultManager] removeItemAtPath:theDirectory error:&error]; } } ``` This hasn't worked and I'm guessing I've missed something stupid but would appreciate any pointers. - Update: The problem was my own stupidity - stray `!` on the second line. Remove it and it works as anticipated.

Original source