在ios中查找给定的文件路径是否有效?

时间:2014-02-06 11:57:54

标签: ios nsfilemanager

我正在尝试创建一个具有接收文件路径(NSString)作为参数的方法的类。

我需要检查给定的文件路径是否有效如果它有效我将在磁盘上执行一些写操作,否则我将返回错误。

那么找出给定路径的最佳方法是有效的吗?

2 个答案:

答案 0 :(得分:3)

无需首先检查路径是否有效。继续尝试创建它,然后检查是否成功。

createFileAtPath:contents:attributes: NSFileManager 的方法返回 BOOL ,如果该文件已存在或成功创建该文件,则返回YES

我建议使用此方法并检查返回的结果。如果它返回NO,则返回错误。

答案 1 :(得分:1)

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

对于你的例子,这将返回

  

的/ var /移动/应用/ 8EFCBF99-BC19-4AFE-934A-B47CBEDF2971 /文件

这对你有帮助吗?我认为该方法包含在使用Core Data的所有Xcode项目类型的AppDelegate中。

以下是一个例子:

NSString *validPath = [[[self applicationDocumentsDirectory] path] stringByAppendingPathComponent:@"test"];
NSString *invalidPath = @"/var/mobile/Applications/abc/test";

if (0 == [validPath rangeOfString:[[self applicationDocumentsDirectory] path]].location) {
    // will be executed
    NSLog(@"Valid path");
}
else {
    NSLog(@"Invalid path");
}

if (0 == [invalidPath rangeOfString:[[self applicationDocumentsDirectory] path]].location) {
    NSLog(@"Valid path");
}
else {
    // will be executed
    NSLog(@"Invalid path");
}