Objective C: convert a NSMutableString in NSString

后端 未结 2 1449
闹比i
闹比i 2021-02-02 05:11

I have an NSMutableString, how can I convert it to an NSString?

2条回答
  •  余生分开走
    2021-02-02 05:32

    Either via:

    NSString *immutableString = [NSString stringWithString:yourMutableString];
    

    or via:

    NSString *immutableString = [[yourMutableString copy] autorelease];
    //Note that calling [foo copy] on a mutable object of which there exists an immutable variant
    //such as NSMutableString, NSMutableArray, NSMutableDictionary from the Foundation framework
    //is expected to return an immutable copy. For a mutable copy call [foo mutableCopy] instead.
    

    Being a subclass of NSString however you can just cast it to an NSString

    NSString *immutableString = yourMutableString;
    

    making it appear immutable, even though it in fact stays mutable.
    Many methods actually return mutable instances despite being declared to return immutable ones.

提交回复
热议问题