gnustep-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Q) NSNumber class factory methods, such as numberWithXXX


From: Richard Frith-Macdonald
Subject: Re: Q) NSNumber class factory methods, such as numberWithXXX
Date: Thu, 16 Mar 2006 05:24:44 +0000


On 16 Mar 2006, at 04:59, Jaeyang Park wrote:

<snip>

I assume the if-statement, "if (self == abstractClass)" checks whether
the message is sent to NSNumber or any of concrete sub classes of
NSNumber.
As in
   [NSNumber numberWithFloat:13.0]      ---- A)

or [NSFloatNumber numberWithFloat:13.0]  ---- B)

<snip>
Well, it would have that effect, but we never call +numberWithFloat: on NSFloatNumber. It's actually to differentiate between messages sent to NSNumber and to (say) MyCustomClass (a subclass of NSNumber written by someone else).

Now, the question is that what is the difference(s) between two body
of statements.
If I follow the second (else-part) part,
I get an instance from one of concrete sub class, in this case of B,
NSFloatNumber

Call it MyCustomClass rather than NSFloatNumber

using Zone. Then, the message initWithFloat: is sent to
that instance. Since, NSFloatNumber does not override initWithFloat:
method, the one in NSNumber will be used.

<snip>
Ah ... but this never happens for NSFloatNumber ... it only ever happens for some subclass you have written ... in which you *should* normally have overridden initWithFloat: If you haven't overridden it ... your class lacks an initialiser, so it will fall back on the implementation in NSNumber ... which will release your custom class instance and provide a working NSFloatNumber instance instead.

<snip>

Am I missing something? (The odds are pretty high in this case, since
I'm a virtually novice in Objective-C and GNUstep/Cocoa/OpenStep)

What this code does is ....

If you call +numberWithFloat: on NSNumber, it returns an instance of a private subclass of NSNumber encapsulating a float. If you call +numberWithFloat: on your own subclass of NSNumber then an instance of your subclass is created if your subclass has the initWithFloat: initialiser, it is called to initialise it. if your subclass does not have the initialiser, the superclass implementation destroys it (because it can't know how to initialise your subclass) and creates an object which will work.







reply via email to

[Prev in Thread] Current Thread [Next in Thread]