Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

objective c - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...