Delete file obj c

Marc picture Marc · Mar 19, 2013 · Viewed 25.2k times · Source

I am creating files with the following code

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *filename = @"xyz123.data";
docPath = [NSString stringWithFormat:@"%@/%@", docPath, filename];

NSError *error = nil;
[data writeToFile:docPath options:0 error:&error];

To delete files I use the following

NSFileManager *manager = [NSFileManager defaultManager];

NSError *error = nil;

NSString *path = @"xyz123.data";
//NSString *path = @"Documents/xyz123.data";
[manager path error:&error];

But neither the first nor the second path seem to work, I always get the error "no such file or directory".

Answer

Aaron Golden picture Aaron Golden · Mar 19, 2013

You used NSHomeDirectory() stringByAppendingPathComponent in the file creation, but not in either path when you try to delete the file. Try:

[manager removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/xyz123.data"] error:&error]