Search code examples
objective-cnsfilemanager

Objective-C: File Manager, trouble deleting a file


I have the following method, which takes in the name of a file as a string, then appends it to the path that is declared outside of the method.

-(BOOL)deleteFile:(NSString *)filename{

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:filename];
NSLog(@"[deleteFile] *myPathsDocs: %@", myPathDocs);

NSLog(@"[deleteFile] about to delete file");
//delete file
BOOL success = [fileManager removeItemAtPath:myPathDocs error:NULL];
NSLog(@"[deleteFile] success? %@", success);


return success;

It deletes the file from the directory, but then the program crashes without returning, or even making it to the

NSLog(@"[deleteFile] success? %@", success);

Any ideas? I think it may be something obvious that I am just not seeing, but I've looked through it many times, and everything seems to be in order.


Solution

  • The variable success is of type BOOL and the %@ format specifier is for objects. So when NSLog tries to use your boolean (which is either 1 or 0) as a pointer, it crashes with a segmentation fault. Use

    NSLog(@"Success: %@", success ? @"YES" : @"NO");
    

    instead.