I heard that Objective-C is influenced by the "message passing mechanism" of SmallTalk.
Objective-C, like Smalltalk, can use dynamic typing: an object can be sent a message that is not specified in its interface. This can allow for increased flexibility, as it allows an object to "capture" a message and send the message to a different object that can respond to the message appropriately, or likewise send the message on to another object.
And I felt for codes like [anObject someMethod]
, the binding of someMethod
to the machine code may happen at run-time..
Therefore, I write a demo like this:
#import <Foundation/Foundation.h>
@interface Person : NSObject {
@private char *name;
}
@property (readwrite, assign) char *name;
- (void)sayHello;
@end
@implementation Person
@synthesize name;
- (void)sayHello {
printf("Hello, my name is %s!\n", [self name]);
}
@end
int main() {
Person *brad = [Person new];
brad.name = "Brad Cox";
[brad sayHello];
[brad sayHelloTest];
}
I tried [brad sayHelloTest]
to send brad
a message sayHelloTest
which brad
doesn't know how to handle with.. I expect the error will NOT happen at compile-time..
However, the compiler still throws an error:
main.m:24:11: error: instance method '-sayHelloTest' not found (return type defaults to 'id') [-Werror,-Wobjc-method-access]
[brad sayHelloTest];
^~~~~~~~~~~~
main.m:3:12: note: receiver is instance of class declared here
@interface Person : NSObject {
^
Change [(id)brad sayHelloTest]
to [(id)brad sayHelloTest];
doesn't work either.. (The compiling command is clang -Wall -Werror -g -v main.m -lobjc -framework Foundation -o main
)
In Objective-C, does the binding of method really happen at "run-time"? If so, why will there be a compiler error like this?
If the binding doesn't happen at "run-time", why was "Objective-C" called "dynamic typing language"?
Does anyone have any ideas about this?