何でもかんでもstringByAppendingPathComponentで連結したら痛い目を見たので、
備忘録として書き残しておく。
ファイルパスの場合
パスを連結したい場合は、NSString の stringByAppendingPathComponent を用いる。
便利な点は、末尾に '/' が付いていない場合は、勝手に付加してくれる。
Objective-C
NSString *path = @"/hoge";
NSLog(@"%@", [path stringByAppendingPathComponent:@"content/"]);
Output
/hoge/content/
※しかし、ファイルパスの場合は問題は無いが、URL文字列を連結すると正しいパス文字列が作られない。
Objective-C
NSString *path = @"http://hoge";
NSLog(@"%@", [path stringByAppendingPathComponent:@"content/"]);
Output
http:/hoge/content/
上記の通り、
スキーム文字列が http:/ となり、正しく扱えなくなる。
URLの場合
URLに関するパス文字列を作る場合は、NSURL の URLByAppendingPathComponent を用いる。
Objective-C
NSString *path = @"http://hoge";
NSLog(@"%@", [[[NSURL URLWithString:path] URLByAppendingPathComponent:@"content/"] absoluteString]);
Output
http://hoge/content/