Ped*_*usa 61 objective-c nsfilemanager
如何检查URL(而不是路径)中是否存在文件,以便将预先填充的默认存储设置到iPhone模拟器中:
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"];
/*
Set up the store.
For the sake of illustration, provide a pre-populated default store.
*/
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:storePath]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Food" ofType:@"sqlite"];
if (defaultStorePath) {
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
}
}
Run Code Online (Sandbox Code Playgroud)
我已经读过,在最近版本的模板中,applicationDocumentsDirectory方法返回一个URL,因此我更改了代码以使用NSURL对象来表示文件路径.但是,在[fileManager fileExistsAtPath:storePath],我需要改变fileExistsAtPath到类似的东西fileExistsAtURL(显然它不存在).
我检查了NSFileManager类参考,但没有找到适合我目的的任何合适的任务.
有什么提示吗?
Mun*_*ndi 120
if (![fileManager fileExistsAtPath:[storeURL path]])
...
Run Code Online (Sandbox Code Playgroud)
从文档:
如果此URL对象包含文件URL(由isFileURL确定),则此方法的返回值适合输入NSFileManager或NSPathUtilities的方法.如果路径具有尾部斜杠,则将其剥离.
vad*_*ian 15
对于文件系统,URL NSURL本身有一种检查URL可访问性的方法
NSError *error;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"];
if ([storeURL checkResourceIsReachableAndReturnError:&error]) {
// do something
} else {
NSLog(@"%@", error);
}
Run Code Online (Sandbox Code Playgroud)
if (![fileManager fileExistsAtPath:[storeURL path]])
Run Code Online (Sandbox Code Playgroud)
没关系,但要小心:对于像这样的网址:
..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50
Run Code Online (Sandbox Code Playgroud)
[storeURL path]会给你那个路径(它适用于[storeURL lastPathComponent]:
..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e
Run Code Online (Sandbox Code Playgroud)
但是如果你在像这样的字符串上使用 lastPathComponent /var/mobile/Applications/DB92F4DC-49E4-4B4A-8271-6A9DAE6963BC/Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50,它会给你1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50
这很好,因为在 url 中,'?' 用于 GET 参数,但如果与字符串混合使用,可能会遇到麻烦。