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: Graham Cox <email@hidden>
- Date: Sun, 23 Feb 2014 20:48:43 +1100
On 23 Feb 2014, at 8:30 pm, email@hidden wrote:
> suppose I think that NSNumber actually is a good fit.
> My usage model requires:
>
> 1. Configure an object with a numeric type: e.g.: @((int)5).
> 2. When I query an object subclass with getValue: I want to receive back an instance of the numeric content with a type as reported by -objCType.
> 3. For any given object subclass (of which there may be many) I want -objCType to be constant.
3. is exactly the reason I called them 'slippery'. The problem is that -objCType does not represent what the number was created with, only what its storage type is. This is explicitly stated in documentation: "Note that number objects do not necessarily preserve the type they are created with".
Chances are with only using integers you're probably OK, but why chance it? There's no contract that says you'll always be safe in this assumption.
In the past I had to preserve numbers with their original types, and to do so reliably I had to create an entire class cluster of my own, even though on the face of it NSNumber looked 'pretty close'. The problem arose with storing a float type that happened to be representable by an integer, 5.0 say. Internally, NSNumber converted that to an integer so its -objCType indicated integer, not float, so the original type information got changed. I can't recall now if this change took place immediately the number was created or at some later stage, for example when a number was copied.
In my case that was unacceptable. As far as I can tell from your example, that will also be unacceptable to you - (int)5 and (float)5.0 will end up as the identical NSNumber, though in your example it appeared to work - but if the internal storage changes at some later stage then you'll be hosed.
--Graham
_______________________________________________
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