Saturday, June 27, 2015
Attempt to mutate immutable object with appendString - ObjectiveC
"Attempt to mutate immutable object with appendString" is one of the most common error while doing iOS development. This will occur due to mutability of the NSString. Lets check in detail.
As most of you know foundation framework has two types of strings
- NSString (not modifiable)
- NSMutableString (can modify)
Basing on these strings, we can have below two scenarios.
1. We can assign NSMutableString to NSString
2. We can't assign NSString to NSMutableString
Scenario #1 is perfectly valid, because NSMutableString is a subclass of NSString. But scenario #2 will crash the application and throws below error message.
"Attempt to mutate immutable object with appendString"
To avoid this problem , while doing #2, you need to make mutableCopy to make a mutable string and assign. Check below for sample code.
//Immutable string , cant modify NSString *firstName = @"Pasumarthi"; //mutable string can modify NSMutableString *nameString = [NSMutableString stringWithString:@"Chandu"]; // invalid - trying to make mutable string to non-mutable string //nameString = firstName; //invalid - we cant make normal string copy to the mutable. //nameString = [firstName copy]; // valid as mutablestring is subclass of string nameString = [firstName mutableCopy]; // valid as mutablestring is subclass of string firstName = nameString; //valid as nameString is mutable [nameString appendString:@" Appu"];
Happy Coding!!!
Subscribe to:
Post Comments (Atom)
Popular Posts
-
A universally unique identifier ( UUID ) is an identifier standard used in software construction, standardized by the Open...
-
Recently I started working on Japser Studio professional for my new project Cloud to generate the reports. I was very new to all cloud ...
-
Below is C program for AVL Tree implementation. #include<stdio.h> #include<malloc.h> typedef struct bst { int info; int hei...
-
strcmp is another string library function which is used to compare two strings and returns zero if both strings are same , returns +ve valu...
-
One of the complex operation on binary search tree is deleting a node. Insertion is easy by calling recursive insertion. But deletion wont...
-
We have recently faced one tricky issue in AWS cloud while loading S3 file into Redshift using python. It took almost whole day to inde...
-
Object slicing: when a derived class object is assigned to a base class object. only base class data will be copied from derived class and...
-
We have faced lot of weird issues while loading S3 bucke t files into redshift. I will try to explain all issues what we faced. Before go...
-
Below code is to find the cube root of a given integer number with out using pow math library function. Its very simple and brute force...
-
Recently we faced one issue in reading messages from SQS in AWS cloud where we are processing same message multiple times. This issue we...
No comments:
Post a Comment