objective-c - 我遇到了 fileExistsAtPath :isDirectory 问题

标签 objective-c cocoa

在我的应用程序中,用户可以通过弹出对话框选择图像。他们第一次这样做时,一切都按预期工作,并且在添加图像期间 fileExistsAtPath:isDirectory 被调用,并且 dir 返回 NO。但是,当用户第二次选择图像时 fileExistsAtPath:isDirectory 始终返回 YES(即使它不是目录)。

-(void) addImagesWithPath:(NSURL *)fileURL recursive:(BOOL) recursive{
  int i, n;
  BOOL dir;
  NSError *error;
  NSURL *newURL;

  [[NSFileManager defaultManager] fileExistsAtPath:[fileURL absoluteString] isDirectory:&dir];

编辑:如果我在方法调用之前添加“dir = NO”,它似乎可以工作,但感觉就像一个黑客。

最佳答案

您应该始终检查 -[NSFileManager fileExistsAtPath:isDirectory:] 的返回值在检查第二个(输出)参数的内容之前。仅当方法返回 YES 时,输出参数才有意义。 。 documentation 中对此进行了描述。 :

Upon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information.

如果该方法返回 NO那么该路径不存在或者您的应用程序无法访问它。如果确实存在,请检查您的路径是否是完整路径(例如,它不应以 ~ 开头)。

此外,您应该使用 -[NSURL path]而不是-[NSURL absoluteString]将路径传递到 NSFileManager 时.

关于objective-c - 我遇到了 fileExistsAtPath :isDirectory 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418121/

相关文章:

ios - @synchronized 指令的使用 - Objective-C Mutex Lock iOS

ios - 如何在 UINavigationController 标题中的图 block 旁边添加图标?

iphone - MFMailComposeViewController 不从 View 中关闭

iphone - 关于在 iPhone 上更新 UITableViewCell 的问题

objective-c - 如何使用 Grand Central Dispatch 启动一个异步调用?

ios - PHImageManager 由于从照片库编辑而错误地获取照片

cocoa - UINavigationController 内的 UITabBar 使用 Storyboard

arrays - 如何在我的 UI 测试中从 XCUIApplication 访问 NSApplicationDelegate

ios - 编辑时调整 UITextField 的大小

objective-c - Cocoa/Obj-C 路径控制 - 你能限制它只选择目录吗?