Search code examples
iosobjective-cnsmutablestringnscountedset

Getting an error when creating an NSMutableString when iterating an NSCountedSet in Objective-C


I am iterating an NSCountedSet in a for-loop, and then trying to create an NSMutableString that is composed of the NSString object it holds, as well as the count for that particular object, and then insert the newly created NSMutableString into an NSMutableArray. However, when I do this, I am getting the following error:

Attempt to mutate immutable object with appendFormat

Here is my code that I am working with:

    for (NSMutableString *myString in myCountedSet) {

        [myString appendFormat:@"-%lu", (unsigned long)[myCountedSet countForObject:myString]];
        [myArray addObject:myString];
    }

I am simply trying to construct a string of the form: myString-count for each object in the NSCountedSet, and then insert this string into an array. Can anyone see what it is I am doing wrong?


Solution

  • Il'm going to guess your strings aren't actually mutable. So change the code to be:

    for (NSMutableString *myString in myCountedSet) {
    
        NSString *combinedString = [NSString stringWithFormat:@"%@-%lu", myString,(unsigned long)[myCountedSet countForObject:myString]];
        [myArray addObject:combinedString];
    }