简体   繁体   English

为什么人们倾向于将NSURL存储为NSString

[英]Why do people tend to store NSURL as NSString

All over the internet as well as here on SO, I see code similar to this 在整个互联网以及SO上,我看到类似的代码

NSString *imageUrl = [NSString stringWithFormat:@"%@",[info valueForKey:UIImagePickerControllerReferenceURL]];

and then 接着

NSURL *url = [[NSURL alloc] initWithString:imageUrl];

Why not just store the NSURL? 为什么不直接存储NSURL? is it because of optimization? 是因为优化? Is NSString that less expensive to store? NSString存储成本更低吗?

A lot of the time, it doesn't seem to be an issue of space (storing an NSString would be more efficient if the NSURL wouldn't contain any other specific data, but not to the point of making a difference in most applications). 很多时候,它似乎不是空间问题(如果NSURL不包含任何其他特定数据,那么存储NSString会更有效,但在大多数应用程序中不会产生差异) 。

Really, the most common reason for storing a URL as string is that it's the way we think of URLs ourselves—simply strings. 实际上,将URL存储为字符串的最常见原因是我们自己想到URL的方式 - 简单地说就是字符串。

In the end, the most applicable/specific choice is generally best— NSURL represents "a URL that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data" ( source ), while an NSString simply represents a string of text—if a URL is what you're going for, use NSURL . 最后,最适用/特定的选择通常是最好的 - NSURL表示“可能包含远程服务器上资源位置的URL,磁盘上本地文件的路径,甚至是任意一段编码数据“( source ),虽然NSString只是表示一串文本 - 如果你正在使用URL,请使用NSURL

(One clear upside to NSString 's is that they're more portable—but NSURL can be serialized and moved about if needed, too!). NSString的一个明显优势是它们更便携 - 但NSURL也可以序列化并在需要时移动!)。

NSString is more universally used. NSString更普遍使用。 For example, AFNetworking uses strings instead of NSURLs. 例如,AFNetworking使用字符串而不是NSURL。 Also, if you need to send this URL to a web server as a parameter you will need it in string format as well. 此外,如果您需要将此URL作为参数发送到Web服务器,您也需要它以字符串格式。

Lazy instantiation is just a good practice in Obj-C. 懒惰实例化只是Obj-C中的一个好习惯。 Create the objects only when you need them. 仅在需要时创建对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM