Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber numberWithFloat vs Init and alloc

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!!!

like image 834
dingerkingh Avatar asked Jan 31 '12 01:01

dingerkingh


2 Answers

[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.

like image 66
Julien Avatar answered Nov 01 '22 06:11

Julien


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.

like image 2
justin Avatar answered Nov 01 '22 05:11

justin