2

I come from a slightly java background as I learned it this year in my Computer Science program. I'm now learning objective-C. What confused me recently was the number object. Why do number objects not have to be initialized. Look below:

    NSNumber *myFloat;

    myFloat = [NSNumber numberWithDouble: 10.09];

When we write our own objects, they always have to be initialized as below;

    someObject x = [[someObject alloc]init]; 

So why is it different here? Is it because the objects we build by default have that as the way to initialize them? Did number objects have their "way to initialize them" changed by the programmers that designed the number object?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Vimzy
  • 1,871
  • 8
  • 30
  • 56

4 Answers4

4

They are initialised. The numberWithDouble: method is equivalent to calling [[NSNumber alloc] initWithDouble:]. In a similar fashion you can make a array with NSArray *array = [NSArray arrayWithObjects:object1, object2] or [NSArray *array = [[NSArray alloc] initWithObjects:object1, object2].

You can also check out this question on the reasoning behind this implementation.

Community
  • 1
  • 1
p4sh4
  • 3,292
  • 1
  • 20
  • 33
3

They are initialized, look at the [[NSNumber alloc] init...] methods. numberWithDouble is a class method that creates an instance of NSNumber via [[NSNumber alloc] initWithDouble:].

Also don't forget the literal for creating NSNumber's

@10.09
@(9 + 1.09)
@YES

and NSDictionary

@{@"key": @"value"}
@{@"enabled": @YES}
Chad Cache
  • 9,668
  • 3
  • 56
  • 48
1

It's just a convenience method to alloc/init an NSNumber instance and set its value to a float. It doesn't mean NSNumber is special and doesn't need alloc/init. You will find methods like this all over Cocoa and Cocoa Touch and you can do the same thing for your custom classes.

Filip Radelic
  • 26,607
  • 8
  • 71
  • 97
0

Internally the implementation of numberWithDouble: would be something like this:

@implementation NSNumber (NSValueCreation)

+ (instancetype) numberWithDouble:(double)value
{
    return [[self alloc] initWithDouble:value];
}

@end

numberWithDouble: is just a convenience wrapper method.

You may also find it useful to create your own convenience methods in some of your own classes.

SomeGuy
  • 9,670
  • 3
  • 32
  • 35