I'm putting together a list of interview questions for someone interviewing to be a Cocoa developer. I'm a programmer, but I've never done Objective-C. I stumbled upon an interesting question that involves dynamic typing. It should be elementary, I've tried it and compiled it, but I'm still not sure how and why it works.
The question is
What happens at compile time and runtime when you do the following:
NSString *s = [NSNumber numberWithInt:3];
int i = [s intValue];
In the debugger I get
i = (int) 3 s = (__NSFCNumber*) 0x383 (invalid address)
The output of NSLog(@"%d",i)
is 3
, and the output of NSLog(@"%@",s)
is 3
.
Can someone give me an explanation of how all of this is handled by the compiler and the runtime system by also trying to keep in mind that I'm completely new to Objective-C and Cocoa, but not at all new to computer science?
Your s is just a standard C pointer, to which an
NSNumber
object (pointer to a) is assigned.NSNumber
, as well asNSString
, responds tointValue
. That's about it.