I have this line of code and am trying to figure out the pros and cons of the way I wrote it. I am just trying to set a label to a float value and both work.... just don't know which is better...
self.display.text=[[NSNumber numberWithFloat:32.445] stringValue];
Is there any difference to say
NSNumber *number = [[NSNumber alloc]initWithFloat:32.445];
self.display.text = [number stringValue];
Well - I know there must be a difference - just not sure what it would be. Seems like the first is more of a wrapper (if that makes sense)?
Thanks!!!
[NSNumber numberWithFloat:32.445]
is equivalent to:
[[[NSNumber alloc] initWithFloat:32.445] autorelease]
in Manual Reference counting mode. In ARC or GC mode, you can consider it equivalent to:
[[NSNumber alloc] initWithFloat:32.445]
Only benefit you might likely get is to try to avoid the autorelease
call in MRC mode and replace it with a release
call.
Seems like the first is more of a wrapper (if that makes sense)?
That is exactly what it is in the majority of implementations, and barring corner cases =p It's called a convenience constructor.
As far as which you should prefer - whatever's clearer to you. I prefer alloc
+init
because it's easier to manage memory and requires slightly less overhead (apart from corner cases).
If you know you have a lot of objects to make or are writing performance/memory critical code (cough iOS devices), then you should consider favoring alloc+init for your 'heavier' code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With