Repository navigation
String Representations of File Paths
对象NSString提供了一套丰富的用于把文件系统路径当作字符串操作的的方法。您可以提取路径的目录,文件名 和扩展名,展开“”表达式(/表示当前用户的主目录)(如:“~me”)。或创建一个针对用户的主目录,并清理包含符号链接的路径,多余的斜杠“/”,并引用路径“.”(表示当前目录)和“..”(表示父目录)。
注意:尽可能使用NSURL的实例来代表(文件)路径————相比处理字符串代表的(文件)路径,操作系统处理URL会更高效。
对象NSString代表路径一般以“/”作为路径分隔符(path separator),以“.”作为扩展分隔符(extension separator)。NSString接受字符串作为路径参数,并将这些一般的路径表示转换为合适的、系统特定的表示形式。在有一个隐含的根目录的操作系统,绝对路径开始于一个路径分隔符(path separator)或者一个“”表达式(“/....”或者“~user/....”)。在必须指定设备时,你可以自己指定,引入一个系统的依赖,或允许字符串对象添加默认设备。
你可以使用stringByStandardizingPath来创建一个(文件)路径的标准表示,这将执行多项任务,包括:
- 扩展一个初始的“~”表达式
- 去除空组件(empty components)的使用,把当前文件路径(“//” and “/./”)以单一路径分隔符表示。
- 在绝对路径中,把父目录的引用(“..”)替换为真正父目录的路径。 例如:
NSString *path = @"/usr/bin/./grep";
NSString *standardizedPath = [path stringByStandardizingPath];
// standardizedPath: /usr/bin/grep
path = @"~me";
standardizedPath = [path stringByStandardizingPath];
// standardizedPath (assuming conventional naming scheme): /Users/Me
path = @"/usr/include/objc/..";
standardizedPath = [path stringByStandardizingPath];
// standardizedPath: /usr/include
path = @"/private/usr/include";
standardizedPath = [path stringByStandardizingPath];
// standardizedPath: /usr/include下面的例子展示了如何使用NSString的实用路径工具和其它的Cocoa函数来获取用户主目录:
// Assuming that users’ home directories are stored in /Users
NSString *meHome = [@"~me" stringByExpandingTildeInPath];
// meHome = @"/Users/me"
NSString *mePublic = [@"~me/Public" stringByExpandingTildeInPath];
// mePublic = @"/Users/me/Public"你可以发现当前用户和给定用户的主目录NSHomeDirectory和NSHomeDirectoryForUser分别为:
NSString *currentUserHomeDirectory = NSHomeDirectory();
NSString *meHomeDirectory = NSHomeDirectoryForUser(@"me");需要注意的是,你通常应该使用函数NSSearchPathForDirectoriesInDomains为当前用户定位标准主目录。例如:你不应该使用
NSString *documentsDirectory =
[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];而应该使用
NSString *documentsDirectory;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0) {
documentsDirectory = [paths objectAtIndex:0];
}对象NSString提供了一套丰富的用于把文件系统路径当作字符串操作的的方法,例如:
| :------------ | :----------- | | pathExtension | The path extension, if any, of the string as interpreted as a path. (read-only) | | stringByDeletingPathExtension | A new string made by deleting the extension (if any, and only the last) from the receiver. (read-only) | | stringByDeletingLastPathComponent | A new string made by deleting the last path component from the receiver, along with any final path separator. (read-only) |
- Introduction
- Strings
- Creating and Converting String Objects
- Formatting String Objects
- String Format Specifiers
- Reading Strings From and Writing Strings To Files and URLs
- Searching, Comparing, and Sorting Strings
- Words, Paragraphs, and Line Breaks
- Characters and Grapheme Clusters
- Character Sets
- Scanners
- String Representations of File Paths
- Drawing Strings
- Document Revision History
- Index