Timothy Rajan
Timothy Rajan

Reputation: 1957

Unable to append String NSMutableString - Error

I have the following code

NSMutableString *ibmcountryCodeLabel=[[NSMutableString alloc]init];
NSMutableString *imobileNumberValue=[[NSMutableString alloc]init];
ibmcountryCodeLabel=@"555";
imobileNumberValue=@"333";
NSLog(@"Done1");
[ibmcountryCodeLabel appendString:imobileNumberValue];
NSLog(@"Done2");

Though both the string are mutable when I try to append one with another I am getting "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'"

read through all the threads. But not able to find a solution. Kindly help me. Thanks for your time

Upvotes: 1

Views: 367

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Here is the problem: this assignment produces a mutable string object:

NSMutableString *ibmcountryCodeLabel=[[NSMutableString alloc]init];

After this assignment, however, the object pointed to by ibmcountryCodeLabel is no longer mutable:

ibmcountryCodeLabel=@"555";

This is because the @"555" constant is an immutable subclass of NSString. Trying to modify it leads to runtime errors.

Change the code as follows to fix this problem:

NSMutableString *ibmcountryCodeLabel=[NSMutableString stringWithString:@"555"];
NSMutableString *imobileNumberValue=[NSMutableString stringWithString:@"333"];

Upvotes: 3

Related Questions