NSString 对象的最大长度是多少?
NSString 对象中可以保存的最大字符串大小是多少?
这会动态变化吗?
What is the maximum sized string that can be held in a NSString object?
Does this change dynamically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设 NSString 的硬限制是 NSUIntegerMax 个字符,因为 NSString 的索引和大小相关的方法返回 NSUInteger。由于当前能够运行 iOS 的所有设备都是 32 位,这意味着 NSUIntegerMax 为 2^32 - 1,并且 NSString 可以容纳略多于 42 亿个字符。
不过,正如其他人指出的那样,实际限制要小得多 - 特别是在 iOS 设备上,在达到 NSString 中的任何硬限制之前,您就会耗尽内存。
I would assume the hard limit for NSString would be NSUIntegerMax characters, since NSString's index and size-related methods return an NSUInteger. Since all devices currently capable of running iOS are 32 bit, this means NSUIntegerMax is 2^32 - 1 and NSString can hold a little over 4.2 billion characters.
As others have pointed out, though, the practical limit is much smaller - on an iOS device especially, you'll run out of memory long before you hit any hard limit in NSString.
NSString
实际上是一个类簇,因此不同的具体类(例如NSString
与NSMutableString
)很可能会让我们用于存储数据的不同“后备存储”。您甚至可以子类NSString
并提供您自己的后备存储实现,以满足您可能有的特定需求(请参阅 NSString 的“子类化注释”)。至于 NSString 实际使用哪个后备存储,这是 Apple 没有记录的实现细节,并且可能随时更改。
就我自己而言,我假设 NSString 的最大长度仅受可用内存的限制。实际上,由于可用内存可能非常巨大,因此还会有一些其他限制(可能与性能相关),但我从未遇到过这样的限制。
NSString
is actually a class-cluster, so it is highly possible that different concrete classes (say,NSString
vs.NSMutableString
) will make us of different "backing stores" for storing the data. You could even subclassNSString
and provide your own backing store implementation, for specific needs you might have (look at "Subclassing Notes" for NSString).As to which backing store is actually used by
NSString
, this is an implementation detail that is not documented by Apple, and it could change at any time.For myself, I assume that the maximum length of an
NSString
is only limited by available memory. Actually, since available memory can be really huge, there will be some other limit (maybe a performance related one), but I have never incurred in such limit.它几乎可以容纳与虚拟内存系统所能表示的一样多的内存。但我个人认为最大长度只限于当时可用的内存。
It can hold almost as much memory as can be represented by virtual memory system. But I personally feel the maximum length is only restricted to whatever memory available at that time.