Reputation: 1681
How does Objective-C provide a "dynamic" runtime? What does "dynamic" refer to here?
Upvotes: 14
Views: 6311
Reputation: 81848
In one sentence: Objective-C decides which method implementation to call right before doing so (during runtime). The idea is that the connection between the name of a method and the implementation is dynamic. C++ for example resolves names during compile time.
Example:
id object = @"1";
int i = [object intValue];
object = @1;
i = [object intValue];
In this example the intValue
message is first sent to an instance of NSString
and then to an NSNumber
. The code emitted by the compiler is identical for both calls–in fact the compiler does not even know to which kind of object it's sending messages to (as the type is id
).
The runtime decides which implementation to call to extract an int value from a string or an NSNumber
.
Upvotes: 23
Reputation: 21966
Dynamic term referes to the binding with the virtual tables.Also known as late binding, if the binding occurs at compile time, then it's not important what is the real object that receives the message, but the important is the type of reference to this object.With the late binding instead, the important is the object (and personally I prefer late binding), so when you override a method this will get called for sure if the object belongs to that class.Consider this class:
@interface Person : NSObject
@end
#import "Person.h"
@implementation Person
- (NSString*) description
{
return @"A good person, smart but lazy";
}
@end
If you try to log the description:
NSObject* obj=[[Person alloc]init];
NSLog(@"%@",obj); // same as NSLog(@"%@",[obj description]);
This logs "A good person, smart but lazy".If the binding with the virtual table was static, it was used the description method of the superclass NSObject, so you would see just the address of the object between braces:
<Person: 0x1001083b0> // Address of the object
In C++ there is the static binding, very annoying to my personal opinion.Java and Objective-C are dynamic.
Upvotes: 1