Doug
Doug

Reputation: 1326

IOS - NSMutableString: appending, and initializing a property

I'm obviously not getting something with this.

I'm parsing an XML Document so I have an NSMutableString to append to for one of the elements because foundCharacters gets cut off and does it in pieces. I can get this all working but I don't understand why doing it in a certain way it does not work.

@property (copy, nonatomic) NSMutableString *currentFoundCharacter;

This is how I declare the property for the ViewController.

Then I have:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
  {
    if (!currentFoundCharacter) {
      currentFoundCharacter = [[NSMutableString alloc] init]; // Have to do this or new strings never append to it.
    }
    if ([currentAttribute compare:@"description"] == NSOrderedSame && currentAttribute.length > 1) {
    [currentFoundCharacter appendString:[string copy]];
  }

Now this right here works. It will combine within a element all that I want. but if I try to use the synthesized methods I get error about mutating an immutable object so basically replace all currentFoundCharacters with self.currentFoundCharacters.

Maybe I misunderstood when and why to use the properties vs instance variables but outside of init methods and such I was under the impression it was better to use the setter / getters. In the end I just want to make sure I make maintainable code.

Upvotes: 0

Views: 1522

Answers (1)

Mario
Mario

Reputation: 4520

Use retain instead of copy in your property. Copy gives you an immutable copy.

Upvotes: 3

Related Questions