基礎篇:
自省是對象的固有能力,即程式運行時,對象可根據請求對外透露自身基本特性。
您可以給對象發送某種訊息,向其詢問與它自身相關的問題,對象在Objective-C 運行時將會向您提供答案。
自省是很重要的編碼工具,它可以讓程式變得更加高效健壯。
所有的繼承了NSObjec的對象有擁有下列三個方法:“
isKindOfClass: 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
方法1的參數值為[NSString class],即發送一個名為class的類方法給一個類而得到。例如:
if ([obj isKindOfClass:[NSString class]]) {
NSString *s = [(NSString *)obj stringByAppendingString:@”xyzzy”];
}
方法3的參數值為一個選取器,如@selector(shoot)。
如果對象中有這個方法shoot,就響應為true。例如:
if ([obj respondsToSelector:@selector(shoot)]) {
[obj shoot];
} else if ([obj respondsToSelector:@selector(shootAt:)]) {
[obj shootAt:target];
}
介紹一種新類型SEL,它是Objective-C用於選取器的類型。
SEL shootSelector = @selector(shoot);
SEL shootAtSelector = @selector(shootAt:);
SEL moveToSelector = @selector(moveTo:withPenColor:);
在NSObject類中,可以通過方法performSelector: 或者 performSelector:withObject:來執資料列選取器。例如:
[obj performSelector:shootSelector];
[obj performSelector:shootAtSelector withObject:coordinate];
在NSArray類中,可以通過makeObjectsPerformSelector:來執資料列選取器操作。例如:
[array makeObjectsPerformSelector:shootSelector]; // cool, huh?
[array makeObjectsPerformSelector:shootAtSelector withObject:target]; // target is an id
在UIButton類中,可以通過 - (void)addTarget:(id)anObject action:(SEL)action ...;方法來執資料列選取器。例如:
[button addTarget:self action:@selector(digitPressed:) ...];
內容來自:
http://mikixiyou.iteye.com/blog/1587051
進階篇:
Runtime of Objective - c
http://blog.sina.com.cn/s/blog_4cd8dd130101juf1.html
http://www.linuxidc.com/Linux/2012-02/54989.htm
http://www.cocoachina.com/macdev/objc/2013/0115/5541.html