-1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
syedfa
  • 2,801
  • 1
  • 41
  • 74

1 Answers1

1

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];
}
Gary Riches
  • 2,847
  • 1
  • 22
  • 19
  • Thanks very much for your prompt reply. Does the line: [myArray combinedString] = [myArray addObject:combinedString] ? – syedfa Feb 11 '15 at 17:13
  • That was a typo, I have fixed it now – Gary Riches Feb 11 '15 at 17:14
  • 1
    Change line 1 to for(NSString *myString in myCountedSet) { ? – KirkSpaziani Feb 11 '15 at 17:42
  • That would be better and would have given you a warning when trying to append. – Gary Riches Feb 11 '15 at 17:44
  • 3
    And - no - do NOT fill the Counted set with NSMutableStrings. Sets rely on their entries being immutable. Think about what would happen if you did something like: NSMutableString *s = [NSMutableString stringWithString: @"whatever"]; [set addObject: s]; [set addObject: s]; // Now you have whatever -> count 2.. Now mutate the string... What happens when you search the set for @"whatever"? – KirkSpaziani Feb 11 '15 at 17:46
  • I would have used `stringByAppendingFormat`. – Hot Licks Feb 11 '15 at 18:08
  • Actually it's a bit more complicated that I'm making out. You can mutate objects in a set, and it will still work for enumeration. The docs indicate that you can. My tests indicate it breaks NSCountingSet's count functionality: for(NSString *str in set) { NSLog(@"%@ - %@", str, @([set countForObject: str])); } returns 0 after mutating the string as I described above. My advice I guess is be very careful with sets... – KirkSpaziani Feb 11 '15 at 18:08
  • I posted this question to attempt to get more info, the answer should be relevant to the initial question here as well: http://stackoverflow.com/questions/28461675/why-dont-nsset-nsmutableset-nscountedset-force-immutable-objects-as-entries – KirkSpaziani Feb 11 '15 at 18:28