Delete file obj c

倖福魔咒の 提交于 2019-12-21 06:50:55

问题


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".


回答1:


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]



回答2:


Try this:

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [docPath stringByAppendingPathComponent:@"xyz123.data"];
NSError *error = nil;
[data writeToFile:filePath options:0 error:&error];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];


来源:https://stackoverflow.com/questions/15505529/delete-file-obj-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!