What is the purpose of having both NSMutableString and NSString?

前端 未结 4 1739
不知归路
不知归路 2020-12-09 23:45

Why does Objective C provide both class NSString and subclass NSMutableString rather than just provide NSMutableString? Isn\'t a NSString equivalent to \"const NSMutableStr

相关标签:
4条回答
  • 2020-12-09 23:50

    I would say the general rule is "don't use a class whose purpose is to provide functionality you don't need". If you need to change the contents of a string directly, use NSMutableString. If not, use NSString. In terms of size and how much heap space they take up, the classes themselves should be pretty similar.

    0 讨论(0)
  • 2020-12-10 00:04

    It is very possible, and even likely, that there are optimizations in place that are only allowed when strings are immutable.

    In fact running

    NSString *A = @"Bob";
    NSString *B = @"Bob";
    

    in the debugger immediately shows that they are both pointers to the same string. In fact

    NSString *C = [NSString stringWithString:@"Bob"];
    NSString *D = [A copy];
    

    both point to the same memory address as well. Meanwhile

    NSString *E = [NSMutableString stringWithString:@"Bob"];
    

    points to a different string.

    So yes, using NSStrings are more efficient in some cases. And in general cocoa lends itself to returning a new copy of a string rather than an edited one. However, I can't really argue that you shouldn't use a mutable string everywhere, but it does seem to go against the general guidelines for the framework.

    In my own work I tend to only use mutable variants where I need to edit things directly. It's just a little backwards from the C/C++ style of everything mutable unless you need a const, everything is const unless you need mutability.

    0 讨论(0)
  • 2020-12-10 00:15

    The reason for both classes is the same reason that you sometimes use a std::string and sometimes use a const std::string. However, unlike C++, Objective-C doesn't have const methods, so they instead separate const- from non-const- methods into two different classes. This is also seen in many of the core classes, such as NSArray (NSMutableArray), NSDictionary (NSMutableDictionary), etc.

    0 讨论(0)
  • 2020-12-10 00:15

    I think the usage of an immutable string is a hint for the compiler which can perform optimizations by knowning it won't change.

    0 讨论(0)
提交回复
热议问题