2012年12月16日 星期日

Objective-C 的精隨

There's three traits that differ objective-C with other object oriented language. They are sort of related but i will introduce them one by one.

Polymorphism: 

Well different class sure can have same name class methods. This is not much different with other object-orient language but will cause much confuse in pure C. But this feature will be very important if combine with following two other objective-c only feature.

 Dynamic Typing:

This together with polymorphism will make codes more reusable since return type and parameters types no longer fixed. This can enables run-time determined object types to call same name methods which can invoke different method calls. ex.
//assume Fraction and Complex class all defined Print but  show different format
id classobj;
aFraction * = [Fraction new];
aComplex *=[Complex new];
classobj = aFraction;
[classobj Print];
classobj = aComplex;
[classobj Print];

Well this is not significantly showing how Dynamic Typing's goodness. But pass attention that id object's method call is determined at runtime by which type of object it contains. This is highly not possible for other language.

Dynamic Binding

This feature means an object can determined at runtime which method it will invoke under circumstances at that time. Introduce selector concept and @selector directive. example as below
SEL action;
id graphicobject;
...
action = @selector (draw) ;
...
[graphicobject performSelector:action];

This will also introduce a series of method that under NSObject the perform support for dynamic typing and dynamic binding feature.

-(BOOL) isKindOfClass:class-object
-(BOOL) isMemberOfClass:class-object
-(BOOL) respondsToSelector:selector
-(BOOL) instancesRespondToSelector:selector
-(BOOL) isSubclassOfClass:class-object
-(id)performSelector:selector
-(id)performSelector:selector withObject:object
-(id)performSelector:selector withObject:object1 withObject:object2

沒有留言:

張貼留言