Tuesday, 15 September 2015

why objective-c does not support same method name in difference class? -



why objective-c does not support same method name in difference class? -

here code snippet learning objective-c 2.0 total code:

classwithfloat.h

#import <foundation/foundation.h> @interface classwithfloat : nsobject { float value; } -(void)setvalue:(float)avalue; @end

classwithfloat.m

#import "classwithfloat.h" @implementation classwithfloat -(void)setvalue:(float)avalue { value = avalue; } @end

classwithint.h

#import <foundation/foundation.h> @interface classwithint : nsobject { int value; } -(void)setvalue:(int)avalue; @end

classwithint.m

#import "classwithint.h" @implementation classwithint -(void)setvalue:(int)avalue { value = avalue; } @end

main.m:

#import <foundation/foundation.h> #import "classwithfloat.h" #import "classwithint.h" int main(int argc, const char * argv[]) { @autoreleasepool { id number = [[classwithint alloc] init]; [number setvalue:3]; } homecoming 0; }

failed compile, after changing classwithint* number works.

error message:

/users/jcyangzh/src/oc/samename/samename/main.m:17:9: multiple methods named 'setvalue:' found mismatched result, parameter type or attributes

but since objective-c somehow dynamic programming language, message phone call translated native c method call.

obj_msgsend(number, @selector(setvalue:), 3)

the obj_msgsend method find class construction number object isa variable. should create no difference between id or classwithint type.

why objective-c compiler not recognize right method?

note: asking question, because having same method name, different argument type different class reasonable me. seems not possible either because compiler limitation or language design (do not supporting method overloading etc).

the problem object typed id within lexical scope. compiler doesn't know method of same name/selector use. have multiple classes have selector different signatures because arguments different types. should avoid id in case or typecast object in message send brackets tell compiler class's method utilize or bracket same message phone call repeatedly in sequence of if ([obj iskindof: checks. (crazy here) or best take hint nsnumber class on method naming conventions , setfloatvalue: , setintvalue: more readable , clear , helps compiler bit.

but time have , id type only, need checking if object iskindof: or asking trouble.

objective-c

No comments:

Post a Comment