How to append a NSMutableString with a NSMutableString?

后端 未结 4 1557
生来不讨喜
生来不讨喜 2020-12-19 00:43
NSMutableString *str, *str1;

//allocation here

i am using [str appendString:str1] is not working. [str appendFormat:str

相关标签:
4条回答
  • 2020-12-19 01:20
    NSMutableString *mystring = [NSMutableString stringWithFormat:@"pretty"];
        NSMutableString *appending = [NSMutableString stringWithFormat:@"face"];
        [mystring appendString:appending];
    

    works for me...

    are you sure the variables have been allocated (correctly?)? No misspellings?

    0 讨论(0)
  • 2020-12-19 01:21

    if str == nil, no call are performed because there is no object allocated to receive the message but no exception are raised (messages sent to nil return nil by design in Objective-C).

    NSMutableString *str, *str1;
    
    str = [NSMutableString stringWithString:@"Hello "];
    str1 = [NSMutableString stringWithString:@"World"]; 
    
    NSMutableString *sayit = [str appendString:str1];
    
    0 讨论(0)
  • 2020-12-19 01:24

    Seems like your're sending a message to nil. nil is NOT an object, it's just nothing. Sending a message to nothing just return nothing. In order to append these strings, you need to initialize to an empty string. Like so:

    NSMutableString *str = [NSMutableString string];
    

    Then your code will work. Like so:

    [str appendString:str1];
    
    0 讨论(0)
  • 2020-12-19 01:29

    Swift version

    Although in Swift it is not the general practice to use NSMutableString, it may at times be necessary. This is how you would do it:

    var str: NSMutableString = NSMutableString()
    var str1: NSMutableString = "some value"
    str.appendString(str1 as String) // str = "some value"
    

    Note that the usual way to append a string in Swift is like this:

    var str = ""
    let str1 = "some value"
    str += str1
    

    where str and str1 are inferred to be of type String.

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