LoginSignup
3
0

More than 5 years have passed since last update.

Objective-C パスの連結について

Last updated at Posted at 2017-11-28

何でもかんでもstringByAppendingPathComponentで連結したら痛い目を見たので、
備忘録として書き残しておく。

ファイルパスの場合

パスを連結したい場合は、NSStringstringByAppendingPathComponent を用いる。
便利な点は、末尾に '/' が付いていない場合は、勝手に付加してくれる。

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に関するパス文字列を作る場合は、NSURLURLByAppendingPathComponent を用いる。

Objective-C
NSString *path = @"http://hoge";
NSLog(@"%@", [[[NSURL URLWithString:path] URLByAppendingPathComponent:@"content/"] absoluteString]);
Output
http://hoge/content/
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0