What characters does a new empty NSString contain?
i created an NSMutableString with t开发者_JAVA技巧he method stringWithCapacity:5 How do i test if characterAtIndex:0 is empty
Empty string contains no characters, even if you created it with non-zero capacity. To check if string is empty simply check its length:
if ([myString length] == 0){
// empty
}
Moreover, trying to access a character at index which is >= of string's length will result in NSRangeException
exception.
The *WithCapacity
methods that we see on NSString
, NSArray
, etc, have nothing to do with pre-populating the contents of the object. They are simply a means by which you can suggest to the object how much it's going to hold. If you suggest a large enough number, it may use a different storage mechanism than if it were a small number.
So in other words, you could do [NSMutableString stringWithCapacity:1234567890]
and it give you exactly the same thing as if you had simply done [NSMutableString string]
, and the -length
of the resulting object will always be 0.
Frankly, the *WithCapacity
methods are pretty useless. I've never found a reason to use them.
精彩评论