Ok, just came across this thing called "casting" in the Obj-C book I'm reading. They show a line of code that says;
Code:
[(NSButton *)sender setHidden:YES];
Now I tried to find more information about this casting, but I can't. I can't find a good description of it in the Objective-C Programming Guide, I can't find it anywhere else in this book. Does anyone know a good link for learning about this thing?
It is a good old C language cast. That's why I think people should learn C before Objective C, because otherwise they don't understand the basic things.
(NSButton*)sender doesn't cast the object, it casts the pointer to the object. "sender" is declared to have type "id", which is just a shortcut for "could be any Cocoa object". If you send a message to an object of type "id", like "setHidden:", the compiler has no idea what kind of object this is, so it cannot warn you if you send a message that the object doesn't understand. At runtime, your program will crash if it is an object that doesn't understand "setHidden:".
By casting sender to "NSButton*" you tell the compiler "I am absolutely sure it is an NSButton or a subclass of NSButton". Now the compiler can warn you if you send a message that an NSButton doesn't understand. A trivial case would be [(NSButton*)sender setHidden] vs. [sender setHidden]. There is no method setHidden without a parameter. When you send it to sender of type id, the compiler won't warn you because it has no idea whether sender could be an object that understands the message or not. When you send it to (NSButton*)sender the compiler can warn you, because it knows an NSButton* doesn't understand that method.
You should always fix warnings. Do this:
Code:
[(NSControl *)view setEnabled:edit];
Just saying: You should not blindly fix the warning with the goal of making the warning go away; you should check it, understand it, and then do the appropriate thing. In this case, yes, you have just checked that view is a control, so it is safe to cast the pointer to "NSControl*. Warning means that the compiler says "this looks like it might be wrong". So you make sure whether it is wrong or not first and either fix what is wrong, or do things to make the compiler not warn you.
The reason why all warnings should be gone is that then you can turn on "Warnings = errors" in the compiler, and the compiler will stop you when you run into a warning that actually _is_ a bug.