參考:http://psvsps2.blogspot.tw/2009/07/cocoa-fundamental-iphone-part2_31.html
動態型別(Dynamically type)和靜態型別(Statically Type)的優劣爭論持續了好一陣子, 動態型別程式語言帶來的靈活性,靜態型別的嚴謹各有千秋,動態型別表現傑出,幾個重要的程式語言如 python , ruby 都有相當亮眼的表現,Objective-C 也是一種動態型別的程式語言,通常動態型別程式語言會提供比較多的自省(introspection)能力,如 runtime 檢查type,檢查method等等。
Objective-C’s runtime support allows you to discover various properties of objects at
execution time. This process is called introspection. You can find out an object’s class and
superclass using the methods class and superclass, as follows:
Class objectsClass;
Class objectsSuperClass;
id anObject;
objectsClass = [anObject class];
objectsSuperClass = [anObject superclass];
蘋果原始資料
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html
Introspection refers to the inherent ability of an object to divulge, upon request, its essential characteristics at runtime. By sending objects certain messages, you can ask them questions about themselves as objects and the Objective-C runtime provides you with answers. Introspection is an important coding tool because it makes your programs more efficient and robust.
因為所有的class都繼承自NSObject,因此有三個方便來辨認現在的狀態
All objects that inherit from NSObject know these methodsisKindOfClass: returns whether an object is that kind of class (inheritance included)
isMemberOfClass: returns whether an object is that kind of class (no inheritance)
respondsToSelector: returns whether an object responds to a given method
例如
You get a Class by sending the class method class to a class :)
if ([obj isKindOfClass:[NSString class]]) {
NSString *s = [(NSString *)obj stringByAppendingString:@”xyzzy”];
}
Types of Introspection Information
TheNSObject protocol, which is adopted by the NSObject class, defines introspection methods that yield the following kinds of information about an object:- Class membership. To determine if an object inherits, directly or indirectly, from a particular class, send it an
isKindOfClass:message and evaluate the result. This method tells you if the object is a direct instance of the given class. You can also use theclassandsuperclassmethods to obtain the class or superclass of an object and then use that result in comparison operations. - Messages responded to. To find out if an object’s class or superclass implements a method, send the object a
respondsToSelector:message. The parameter is aSEL-typed value constructed from the signature of the method using the@selectordirective. For example:
BOOL doesRespond = [anObject respondsToSelector:@selector(writeToFile:atomically:)];
- Protocol conformance.
If a class conforms to a formal protocol, you can expect it to
implement the required methods of that protocol and send messages to it
accordingly. Use the
conformsToProtocol:method to obtain this information. You specify the argument of this method using the@protocoldirective.