objective-cnsmutablestring

How to pass a parameter of type NSMutableString


I am learning objective-c and as i am trying to pass a parameter to a method RequestExecuteCountLettersForString that accepts data of type NSMutableString i received a warning.

i am passing the textual parameter as follows:

[delegatee RequestExecuteCountLettersForString:@"XYZ"];

and I am receiving this warning:

Incompatible pointer types sending 'NSString *' to parameter of type 
'NSMutableString *'

please let me know how to fix this warnign and why i cant pass such textual input to the method.


Solution

  • The literal @"XYZ" is not an NSMutableString. It's an NSString. That is what the error is telling you.

    You need to pass an actual mutable string.

    NSMutableString *str = [NSMutableString stringWithString:@"XYZ"]; // or [@"XYZ" mutableCopy];
    [delegatee RequestExecuteCountLettersForString:str];
    

    Two things:

    1. Why does your method take a mutable string? If the idea is that the method modifies the mutable string so the result can be used by the caller, then a better approach is to pass in a non-mutable string and have the method use a return value to return a new string. If the only reason it takes a mutable string is because internally the method makes some changes but the caller doesn't need to be aware of those changes, then you definitely should not make the caller pass in a mutable string. So either way, it is probably incorrect to have a parameter of NSMutableString instead of NSString.
    2. Method names should start with lowercase letters. Same for variables and properties. Class names start with uppercase letters.