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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…