什么时候应该使用NSURL而不是NSString,反之亦然? [英] When should I use NSURL instead of NSString and vice versa?

查看:214
本文介绍了什么时候应该使用NSURL而不是NSString,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是有关问题的问题。

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.

在处理从服务器上传和下载文件到我的应用程序时,我总是在使用 NSURL NSString 之间撕裂所有东西路径相关。当然,当有一个现有的API,我只是使用它根据规格。但是当我存储我自己的路径或创建处理他们的自定义类时,我困惑了哪两个是更好的选择。

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 无处不在,它有方便的方法,如 stringByAppendingPathComponent: stringByAppendingPathExtension:。我可以通过使用 [NSURL URLWithString:@string] 创建一个新实例,然后调用 [url path] ] 。但是区别是有原因的,对吧?

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?

当我看看NSFileManager的头文件时,我的混乱增长。这两个方法非常接近:

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);

为什么我会选择使用一个,特别是当两者之间的转换如此轻松?为什么苹果会遇到使用这两种数据类型创建近乎相同的API的麻烦?

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?

如果有人更深入地了解何时使用NSURL而不是NSString你自己的类处理文件路径和远程url,请分享!干杯。

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.

推荐答案

一般来说,对于路径相关操作,您应该优先 NSURL over NSString ,因为路径信息可以更有效地存储在 NSURL 中(根据 NSFileManager )。所以我建议你的API也使用 NSURL

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.

也可以 NSURL URLByAppendingPathComponent: URLByAppendingPathExtension:,因此方便: - )

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

这篇关于什么时候应该使用NSURL而不是NSString,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆