Im trying to learn obj-c and here’s something I dont understand. I know some c# so could someone try to explain this in in a c#y-way I maybe could understand it better 🙂
#import <Foundation/Foundation.h> @interface Car : NSObject
@interface Car : NSObject
{
int year;
NSString *make;
NSString *model;
}
**- (void) setMake:(NSString *) aMake andModel:(NSString *) aModel andYear: (int) aYear;**
- (void) printCarInfo;
- (int) year;
@end
I think i understand the declarations of the variables, but i dont get it for the metod(s?). Can someone explain what this do (bold code)?
The concept which is missing from your learning is “selector”. It’s essentially like “decorating” a method signature with more semantics than you can get with parenthesized parameter-passing. We tend to use descriptive, sentence-like “selectors” for our method prototypes. As an example, consider this basic function:
in Objective-C, we would write it like this:
and the “selector” (which is a first-class concept in Objective-C) is setWith:height: (including the colons, but not anything else). That’s the thing that uniquely identifies that method on that class.
Calling that method happens at runtime when you send a message to that object with arguments placed after the colons in the selector. So a message has three essential components: a recipient, a selector, and the well-placed arguments:
Here,
anObjectis the recipient,setWidth:height:is the selector (helps the runtime find the method), and the arguments are:newWidth = 1024; newHeight = 768;.Then in the implementation of the method, simply use newWidth and newHeight like you would expect:
It may seem awkward and superfluous at first, but after you get used to it, you will prefer it and find yourself writing longer, more semantic function names in other languages.
The concepts associated with selectors are all better understood when learned along with some of the basics of the Objective-C runtime, specifically the concept of “sending messages” (instead of “calling methods”) and the fact that at runtime, not compile-time the actual method is looked-up based on the selector you use in the message. The fact that this happens at runtime gives remarkable flexibility for highly dynamic architectures.