使用NSURL测试文件存在 [英] Testing file existence using NSURL

查看:108
本文介绍了使用NSURL测试文件存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Snow Leopard推出了许多新方法来使用NSURL对象来引用文件,而不是路径名或Core Services的FSRefs。

Snow Leopard introduced many new methods to use NSURL objects to refer to files, not pathnames or Core Services' FSRefs.

但是,我有一个任务找到一个基于URL的方法:测试文件是否存在。我正在寻找一个基于网址的版本 - [NSFileManager fileExistsAtPath:] 。像这样的方法,如果URL描述任何东西,无论它是一个常规文件,目录,或其他任何东西,它应该返回 YES

However, there's one task I can't find a URL-based method for: Testing whether a file exists. I'm looking for a URL-based version of -[NSFileManager fileExistsAtPath:]. Like that method, it should return YES if the URL describes anything, whether it's a regular file, a directory, or anything else.

我可以尝试查找各种​​资源值,但是没有一个明确保证不存在,如果文件不存在,例如

I could attempt to look up various resource values, but none of them are explicitly guaranteed to not exist if the file doesn't, and some of them (e.g., NSURLEffectiveIconKey) could be costly if it does.

我可以使用NSFileManager的 fileExistsAtPath:,但如果有一个更现代的方法,我更喜欢使用。

I could just use NSFileManager's fileExistsAtPath:, but if there's a more modern method, I'd prefer to use that.

在Cocoa,CF或Core中有一个简单的方法或函数确保/记录下来的服务是否给定的文件(或文件引用)URL指向的文件系统对象是否存在?

Is there a simple method or function in Cocoa, CF, or Core Services that's guaranteed/documented to tell me whether a given file (or file-reference) URL refers to a file-system object that exists?

推荐答案

NSURL有这种方法:

NSURL does have this method:

- (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error

哪个返回是否可以到达由文件URL指向的资源

Which "Returns whether the resource pointed to by a file URL can be reached."

NSURL *theURL = [NSURL fileURLWithPath:@"/Users/elisevanlooij/nonexistingfile.php" 
               isDirectory:NO];
NSError *err;
if ([theURL checkResourceIsReachableAndReturnError:&err] == NO)
    [[NSAlert alertWithError:err] runModal];

这篇关于使用NSURL测试文件存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆