What is the maximum length of an NSString object?

2019-01-06 19:03发布

问题:

What is the maximum sized string that can be held in a NSString object?

Does this change dynamically?

回答1:

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.



回答2:

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 subclass NSString 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.



回答3:

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.