Memory management within a message
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];
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];
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.
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]];
精彩评论