Search code examples
objective-cfor-loopnsstringnsmutablestringnsentitydescription

Why can't I appendString in a for Loop?


I have the following code that I'm attempting to simply loop through an entity and for each NSPropertyDescription name, append it to a Mutable string that I'll be building a further string out of.

   - (void) createCSV {
    NSEntityDescription *anEntity = [NSEntityDescription entityForName:@"Missions" inManagedObjectContext:self.missionDatabase.managedObjectContext];

    NSMutableString *csvString = [NSString string];

    for (NSPropertyDescription *property in anEntity) {
        [csvString appendString:property.name];
    }
    NSLog(@"%@",csvString);
}

The problem when running the following code is I get a

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'

I can't figure out what I'm doing wrong. Can I not append an NSString to an NSMutableString?


Solution

  • Look again. csvString isn't mutable. You're creating an NSString. Creating an NSMutableString looks like this:

     NSMutableString *csvString = [NSMutableString string];