Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use NSURL instead of NSString and vice versa?

This is not a question about a pertinent problem. It's a question by which I try to deepen my understanding of Objective-C or more specific Cocoa Foundation.

When dealing with uploading and download files from a server to my apps, I'm constantly torn between using NSURL or NSString for all things path related. Of course when there's an existing API I just use it according to the specs. But when I store my own paths or create custom classes that deal with them, I'm confused which of the two would be the better pick.

NSString is used everywhere and it has convenience methods like stringByAppendingPathComponent: and stringByAppendingPathExtension:. I can easily convert to NSURL by creating a new instance with [NSURL URLWithString:@"string"] and the other way around by calling [url path] on an NSURL instance. But the difference is there for a reason, right?

My confusion grows when I look at header files of something like NSFileManager. These two methods are pretty close together:

- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
- (BOOL)copyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL error:(NSError **)error NS_AVAILABLE(10_6, 4_0);

Why would I choose to use one over the other, especially when conversions between the two are made so easily? And why does Apple go through the trouble of creating near-identical APIs for using both data types?

If someone has the deeper insight for when to use NSURL instead of NSString for your own classes handling file paths and remote urls, please do share! Cheers.

like image 825
epologee Avatar asked Feb 03 '23 12:02

epologee


2 Answers

NSUrl knows how to handle virtually any king of urls — not just Web-adresses and splits it into easy accessible chunks:

  • protocol or scheme (http, ftp, telnet,ssh)
  • username and the password (for example for ssh: ssh://user:[email protected])
  • host name
  • port
  • path
  • GET parameters

Now you can easily asks the url-object for this chunks, while in a string there might be the need for excessive if rules or complicated regex's.

like image 171
vikingosegundo Avatar answered Feb 05 '23 19:02

vikingosegundo


Generally for path related operations you should prefer NSURL over NSString because the path information can be stored more efficiently in NSURL (according to the class reference for NSFileManager). So I would recommend that for your APIs you use also NSURL.

Also NSURL has URLByAppendingPathComponent: and URLByAppendingPathExtension: so convenience is served as well :-)

like image 36
Alfonso Avatar answered Feb 05 '23 19:02

Alfonso