object-c提供了一批用於檢測一個對象是不是某個類的對象或成員,它們是isKindOfClass,isMemberOfClass,respondsToSelector,instancesRespondToSelector,performSelector等,
下面給出了這些函數的一些用法。
1.代碼:
// MyRectangle類和Square類略(它們的定義見前一節“8.object-c的繼承”),
// main.m
#import "Square.h"
#import "MyRectangle.h"
#import <stdio.h>
int main( int argc, const char *argv[] ) {
MyRectangle *rec = [[ MyRectangle alloc] initWithWidth: 10 height: 20];
Square *sq = [[Square alloc] initWithSize: 15];
// isMemberOfClass
// true
if ( [sq isMemberOfClass: [Square class]] == YES ) {
printf( "square is a member of square class\n" );
}
// false
if ( [sq isMemberOfClass: [ MyRectangle class]] == YES ) {
printf( "square is a member of MyRectangle class\n" );
}
// false
if ( [sq isMemberOfClass: [NSObject class]] == YES ) {
printf( "square is a member of object class\n" );
}
// isKindOfClass
// true
if ( [sq isKindOfClass: [Square class]] == YES ) {
printf( "square is a kind of square class\n" );
}
// true
if ( [sq isKindOfClass: [ MyRectangle class]] == YES ) {
printf( "square is a kind of MyRectangle class\n" );
}
// true
if ( [sq isKindOfClass: [NSObject class]] == YES ) {
printf( "square is a kind of object class\n" );
}
// respondsToSelector
// true
if ( [sq respondsToSelector: @selector( setSize: )] == YES ) {
printf( "square responds to setSize: method\n" );
}
// false
if ( [sq respondsToSelector: @selector( nonExistant )] == YES ) {
printf( "square responds to nonExistant method\n" );
}
// true
if ( [Square respondsToSelector: @selector( alloc )] == YES ) {
printf( "square class responds to alloc method\n" );
}
// instancesRespondToSelector
// false
if ( [ MyRectangle instancesRespondToSelector: @selector( setSize: )] == YES ) {
printf( " MyRectangle instance responds to setSize: method\n" );
}
// true
if ( [Square instancesRespondToSelector: @selector( setSize: )] == YES ) {
printf( "square instance responds to setSize: method\n" );
}
// free memory
[rec release];
[sq release];
return 0;
}
2. 運行結果:
$ ./main.exe
square is a member of square class
square is a kind of square class
square is a kind of MyRectangle class
square is a kind of object class
square responds to setSize: method
square class responds to alloc method
square instance responds to setSize: method
3.說明:
(1) 請和jave的instanceof相比較;
(2) 請和java的 getClass相比較;
(3) 所有繼承人自 NSObject 都有一個 class method。