PDA

View Full Version : incompatible pointer type




at0m87
Mar 10, 2012, 02:07 AM
Hi guys.

i have this 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.



xStep
Mar 10, 2012, 02:58 AM
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.
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.



NSMutableString *urlString = [NSString stringWithString: projectNameTF.text]; // non-retained

NSMutableString *urlString = [[NSString alloc] initWithString: projectNameTF.text]; // retained

Guiyon
Mar 10, 2012, 07:35 AM
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.



NSMutableString *urlString = [NSString stringWithString: projectNameTF.text]; // non-retained
NSMutableString *urlString = [[NSString alloc] initWithString: projectNameTF.text]; // retained


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):

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

xStep
Mar 10, 2012, 01:07 PM
D'oh! Thanks for pointing that out.

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):

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