开发者

Cocoa: NSMutableString gives warning with stringValue

This works:

NSString *myVar = @"whatever"; 

NSDecimalNumber *myNum = [NSDecimalNumber decimalNumberWithString:@"10"];

myVar = [myNum stringValue];

This version with mutable string produces warning "assignment from distinct Objective-C type":

NSMutableString *myVar = [NSMutableString stringWithString:@"whatever"];  //UPDATE: CORRECTED CODE

NSDecimalNumber *myNum = [NSDecimalNumber decimalNumberWithString:@"10"];

myVar = [myNum stringValue];

In both cases stringValue is returning an NSCFString. The immutable NSString variable doesn't care, the mutable NSMutable开发者_JAVA百科String complains.

P.S. someone please add tags for NSMutableString and stringValue.


-stringValue returns autoreleased instance of NSString, that is immutable object. Even if you assign it to the mutable string pointer it will not make the string mutable and you will not be able to call mutable string methods on it (btw, the same stays true for your 1st code):

NSMutableString* tStr = @"lala";
[tStr appendString:@"lalala"]; // CRASH! Attempting to mutate immutable object

The correct way to handle it is to create mutable string with convinience method:

NSMutableString* tStr = [NSMutableString stringWithString:@"lala"];
[tStr appendString:@"lalala"]; // OK 


[myNum stringValue] returns a NSString, not NSMutableString, so this will generate the warning.

If you would try to manipulate the instance of myVar later on (assuming it's a mutable string), you would get an exception, because the object is not a mutable string at all.


You cannot make an immutable string into a mutable one simply by assigning it to a variable of type NSMutableString *. What you're doing is essentially:

NSString *immutableStr = @"Mayonnaise";
NSMutableString *mutableStr = immutableStr;

Both variables in this case point to exactly the same constant string object (the pointers will compare equal). You will also get a warning because you are attempting to set a variable of type NSMutableString * with an incompatible value of type NSString *. It is incompatible because NSMutableString * provides methods and behaviour that NSString * doesn't, so when you try to use NSMutableString's behaviour, you will get runtime errors because the actual object being pointed to by the variable is not an NSMutableString.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜