Re: NSNumber : method to return pointer to represented value
Re: NSNumber : method to return pointer to represented value
- Subject: Re: NSNumber : method to return pointer to represented value
- From: Jonathan Hull <email@hidden>
- Date: Sun, 23 Feb 2014 05:31:39 -0800
On Feb 23, 2014, at 4:08 AM, email@hidden wrote:
>> 1(int) and 1(float) can be represented by the same NSNumber object perfectly legally.
> Is that true?
Yes. As far as NSNumber is concerned, they are equal. They are also both equal to @(YES) which is initialized with a BOOL. Once a value is in an NSNumber, it looses its original type identity, and is simply a number. You can get back any representation you like using the value methods. -getValue allows you to get it back into a scalar, but not necessarily the same type you started with.
I was writing a math program a while back and ran into this exact gotcha. I really wanted an -isFloat method, but it seemed to randomly store some floats as ints. That was before tagged pointers though, so the implementation may have changed (and may change again).
I wouldn’t rely on any undocumented implementation differences. Down that path, madness lies…
If you needed to store the creation method, you could write a wrapper around NSNumber (A subclass also works if you really need to pass it somewhere as an NSNumber, but there are gotchas as it is a class cluster). Basically write a class ‘MyNumber’ which stores a NSNumber as it’s instance variable, and then forwards all of it’s methods to it. You can store the type info in that class as it is created. You can also override -isEqual: to have the behavior you want (1 != 1f).
Thanks,
Jon
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden