Wednesday, October 3, 2012

Objective C - missing documents directory

Did you know that by using "removeItemAt:" method in NSFileManager you could actually delete the documents directory? It is bit of a scary thought and I sometimes feel that it shouldn't be the case to keep careless developers away from bugs, but unfortunately or not it is possible.
A possible bug you will miss out because of poor validation would be,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *deleteFilePath = [NSString stringWithFormat:@"%@/%@",[self getFilePath]];
[NSFileManager removeItemAt:deleteFilePath error:nil];

In the above example you should always make sure that the length of the string returned from "getFilePath" is greater than "0". Else you will accidentally delete your documents directory. Therefore the code should look something like,

NSString *file = [self getFilePath];
if (![file isEqual:[NSNull null]] && (file != nil)){
if ([file length] > 0){
NSString *deleteFilePath = [NSString stringWithFormat:@"%@/%@",[self getFilePath]];
[NSFileManager removeItemAt:deleteFilePath error:nil];
}
}

No comments: