Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 NSMutableString complains.

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

like image 358
StringSection Avatar asked Jan 19 '10 08:01

StringSection


2 Answers

-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 
like image 94
Vladimir Avatar answered Sep 21 '22 20:09

Vladimir


[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.

like image 44
Philippe Leybaert Avatar answered Sep 25 '22 20:09

Philippe Leybaert