incompatible pointer type

Discussion in 'iPhone/iPad Programming' started by at0m87, Mar 10, 2012.

  1. macrumors newbie

    Joined:
    Mar 2, 2012
    #1
    Hi guys.

    i have this code

    Code:
    NSMutableString *urlString = urlTextField.text;
    
    and a warning: incompatible pointer type initializing 'NSMutableString *' with an expression of type 'NSString *'

    What does this warning means and how could i fix it? Note that i could still run the code and it works as it should be.
     
  2. macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #2
    You are not copying the string, but the pointer value. The system is recognizing that you are trying to assign the pointer of of non-mutable string to a mutable string. That doesn't make sense since if you tried altering the urlString after this assignment, what you'd really be attempting is an alteration to projectNameTF.text.

    You can do the following casting to get rid of the warning, but that isn't what your want.
    Code:
    NSMutableString *urlString = (NSMutableString* )projectNameTF.text;

    If you plan to manipulate urlString, which declaring it as a mutable string suggests, then you should copy the content of projectNameTF.text to the urlString variable. One of the following two methods are acceptable, depending on the life of urlString.


    Code:
        
        NSMutableString *urlString = [NSString stringWithString: projectNameTF.text]; // non-retained
    
        NSMutableString *urlString = [[NSString alloc] initWithString: projectNameTF.text]; // retained
    
     
  3. macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #3
    That's still going to print an error since you're still creating an NSString, not an NSMutableString. If he wants a mutable string, you'll need something like one of the below (depending on whether he needs a retained or non-retained copy):

    Code:
    NSMutableString *urlString_0 = [NSMutableString stringWithString:projectNameTF.text];
    NSMutableString *urlString_1 = [projectNameTF.text mutableCopy];
    NSMutableString *urlString_2 = [[NSMutableString alloc] initWithString:projectNameTF.text];
    
     
  4. macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #4
    D'oh! Thanks for pointing that out.

     

Share This Page