views:

36

answers:

3

Take the line

[angleLabelInRadians setText:[[NSString alloc] initWithFormat:@"%.3g", [poly angleInRadians]]]; 

When creating an NSString object within a message, do I still need to release this NSString and, if so, how would I do that, given that I haven't created a pointer to the object?

Furthermore, is this correct coding procedure, or is this line too long? Would it be better to split it up in the following form?

NSString *polyRad = [[NSString alloc] initWithFormat:@"%.3g", [poly angleInRadians]];
[angleLabelInRadians setText:polyRad];
[polyRad release];
+2  A: 

There is simple rule: release every object you have created with "init" or "new". In the sample above you can call "autorelease" to free the string or static initializer like [NSString stringWithFormat:...] - it uses autorelease internally.

Gobra
+2  A: 

Unless you're in an enviornment without an autorelease pool, you'll most often just go with one of the convenience functions to do the above.

[angleLabelInRadians setText:[[NSString stringWithFormat:@"%.3g", [poly angleInRadians]]; 

If you do not want to use autoreleasing, you would have to do

NSString *s = [[NSString alloc] initWithFormat:@"%.3g", [poly angleInRadians]];
[angleLabelInRadians setText:s];
[s release];
Kalle
+1  A: 

You have two options :

The one that you suggered : split in three statement.

Personally I think it's better. You have a clear idea of what you are doing just by looking at these tree lines. It's not that clear what you wanted to make in one line. (But that's my personal opinion)

Or you can always do like Grobra said and autorealease the string.

Using a convinience method

[angleLabelInRadians setText:[NSString stringWithFormat:@"%.3g", [poly angleInRadians]]];

Or simply autorelease the string

[angleLabelInRadians setText:[[[NSString alloc] initWithFormat:@"%.3g", [poly angleInRadians]] autorelease]];
gcamp
init + autorelease is the exact same thing as the convenience method so not sure why you'd ever want to do that, when there's a class method for it.
Kalle