如何检查文件是否存在于 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];
}
}
我读过在最新版本的模板中,applicationDocumentsDirectory 方法返回一个 URL,因此我更改了代码以使用 NSURL 对象来表示文件路径。但在 [fileManager fileExistsAtPath:storePath]
,我需要将 fileExistsAtPath
更改为 fileExistsAtURL
(显然它不存在)。
我检查了 NSFileManager 类参考,但没有找到适合我目的的合适任务。
请问有什么提示吗?
if (![fileManager fileExistsAtPath:[storeURL path]])
...
如果此 URL 对象包含文件 URL(由 isFileURL 确定),则此方法的返回值适合输入到 NSFileManager 或 NSPathUtilities 的方法中。如果路径有尾部斜杠,则将其剥离。
对于文件系统 URL,NSURL
本身具有检查 URL 可访问性的方法
NSError *error;
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Food.sqlite"];
if ([storeURL checkResourceIsReachableAndReturnError:&error]) {
// do something
} else {
NSLog(@"%@", error);
}
if (![fileManager fileExistsAtPath:[storeURL path]])
没关系,但要小心:对于这样的网址:
..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50
[storeURL path]
将为您提供该路径(它适用于 [storeURL lastPathComponent]
:
..../Documents/1158a3c96ca22c41b8e731b1d1af0e1e
但是如果你在像 /var/mobile/Applications/DB92F4DC-49E4-4B4A-8271-6A9DAE6963BC/Documents/1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50
这样的字符串上使用 lastPathComponent,它会给你 1158a3c96ca22c41b8e731b1d1af0e1e?d=mm&s=50
这很好,因为在 url 中,'?'用于GET参数,但如果与字符串混合,可能会遇到麻烦。
不定期副业成功案例分享
[url absoluteString]
时出错。不要使用绝对字符串。干杯。