Hello.
I'm new to obj-c. I'm currently reading Chapter 9 in this book (4e, 1st printing), and don't know whether my questions are answered in the later chapters.
Q1:
Program 9.2:
int main (int argc, char * argv[])
{
@autoreleasepool {
id dataValue;
Fraction *f1 = [[Fraction alloc] init];
Complex *c1 = [[Complex alloc] init];
[f1 setTo: 2 over: 5];
[c1 setReal: 10.0 andImaginary: 2.5];
// first dataValue gets a fraction
dataValue = f1;
[dataValue print];
// now dataValue gets a complex number
dataValue = c1;
[dataValue print];
}
return 0;
}
Program 9.2 is supposed to work without any warning/error. But anther example in Chapter 9
id dataValue = [[Fraction alloc] init];
...
[dataValue setReal: 10.0 andImaginary: 2.5];
is supposed to produce a warning message.
I wonder why there's difference between these 2 examples ? They both assign a Fraction object to an id variable.
Q2:
There's a method of NSObject:
-(BOOL) respondsToSelector: selector
In Chapter 9
The test
if ( [Square respondsToSelector: @selector (alloc)] == YES )
tests whether the class Square responds to the class method alloc, which it does because it’s inherited from the root object NSObject. Realize that you can always use the class name directly as the receiver in a message expression, and you don’t have to write this in the previous expression
(although you could if you wanted):
[Square class]
That’s the only place you can get away with that. In other places, you need to apply the class method to obtain the class object.
Since respondsToSelector is an instance method, why is it able to be used to send message to an class object?
And it says we can use class name instead of class object here. Is it only a exceptional shortcut, or is there any mechanism behind this?
Thanks in advance!