Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending Strings to NSMutableString

Been looking at this for a bit now and not understanding why this simple bit of code is throwing an error. Shortened for brevity:

NSMutableString *output;

...

@property (nonatomic, retain) NSMutableString *output;

...

@synthesize output;

...

// logs "output start" as expected
output = [NSMutableString stringWithCapacity:0];
[output appendString:@"output start"];
NSLog(@"%@", output);

...

// error happens here
// this is later on in a different method
[output appendString:@"doing roll for player"];

Can anyone spot my mistake?

like image 741
typeoneerror Avatar asked Apr 01 '10 05:04

typeoneerror


2 Answers

Change the line

output = [NSMutableString stringWithString:@"output start"]

to

[self setOutput:[NSMutableString stringWithString:@"output start"]]

(or self.output = ... if you prefer that notation).

Although you have declared a property, you are not using the setter, so you are not retaining the string.

like image 159
Nick Moore Avatar answered Oct 20 '22 00:10

Nick Moore


The solution did in fact have to do with retention, as indicated by user invariant. The class method:

output = [NSMutableString stringWithCapacity:0];

returns an autorelease NSMutableString. When assigned to my output property -- seemingly, even with the retain flag -- it did not retain it. The solution was to alloc it myself and not autorelease:

output = [[NSMutableString alloc] initWithCapacity:0];

Then the retain worked. Any explanation as to why would be very welcome.

Edit

Figured out why. I was accessing the instance vars directly instead of through the getter/setter that I synthesized. More info on my blog.

like image 33
typeoneerror Avatar answered Oct 19 '22 22:10

typeoneerror