Hi Everyone,
I'm fairly new to Objective-C and I come from a C and Java background. I just had a question about messages. I know it's similar to calling a function/method but the object may choose to ignore it or forward the message. Ok, I got that.
So I did some playing around just to learn ObjC and I'm getting confused a message call.
I had two classes, Test1 and Test2. Both implement an "add" function.
Test1's add takes in a Test1 object as an argument. This is similar to Test2.
Here is the code:
Test1 test1 = [[Test alloc] init];
Test2 test2 = [[Test2 alloc] init];
id value1 = test1;
id value2 = test2;
id value3 = nil;
value3 = [value1 add: value2];
My confusion is that even though it compiles, I don't get a runtime error. It executes just fine even tho the argument for Test1's add requires a Test1 object, yet if you see here, I'm passing in a Test2 object. Shouldn't the compiler look up the "add" method/function from value1 (which is a Test1 object)?
How come there is no runtime error? I know it has something to do with dynamically typed variables, but Test1's add function requires a Test1 object. So, when a message is sent, it goes to a selector and calls the appropriate function regardless of the argument types??
Coming from a statically typed background, this kinda confuses me. Could someone explain? Hopefully, my question is easily understandable. If not, please let me know.
Many thanks.
I'm fairly new to Objective-C and I come from a C and Java background. I just had a question about messages. I know it's similar to calling a function/method but the object may choose to ignore it or forward the message. Ok, I got that.
So I did some playing around just to learn ObjC and I'm getting confused a message call.
I had two classes, Test1 and Test2. Both implement an "add" function.
Test1's add takes in a Test1 object as an argument. This is similar to Test2.
Here is the code:
Test1 test1 = [[Test alloc] init];
Test2 test2 = [[Test2 alloc] init];
id value1 = test1;
id value2 = test2;
id value3 = nil;
value3 = [value1 add: value2];
My confusion is that even though it compiles, I don't get a runtime error. It executes just fine even tho the argument for Test1's add requires a Test1 object, yet if you see here, I'm passing in a Test2 object. Shouldn't the compiler look up the "add" method/function from value1 (which is a Test1 object)?
How come there is no runtime error? I know it has something to do with dynamically typed variables, but Test1's add function requires a Test1 object. So, when a message is sent, it goes to a selector and calls the appropriate function regardless of the argument types??
Coming from a statically typed background, this kinda confuses me. Could someone explain? Hopefully, my question is easily understandable. If not, please let me know.
Many thanks.