这一章主要讲述了多态的概念,怎样实施动态绑定
1. 多态:多态就是不同的类中有相同名称的方法。
2. 动态绑定和id类型
id类型的对象可以接受一切类型的对象。
声明的时候无需添加*号
如:
id valueObject = [[Fraction alloc] init]
可以利用id类型的这种特性,进行动态编程。
注意:
1)id类型的对象不能使用点运算符。
2)如果一个方法被定义在你的多个类中。保证这个方法的参数和返回值类型保持一致。
3. 问类问题
objective-c 为了保证动态编程的可靠性,提供了一系列方法。
#import "Square.h"
int main (int argc, char * argv[])
{
@autoreleasepool {
Square *mySquare = [[Square alloc] init];
// isMemberOf:
if ( [mySquare isMemberOfClass: [Square class]] == YES )
NSLog (@"mySquare is a member of Square class");
if ( [mySquare isMemberOfClass: [Rectangle class]] == YES )
NSLog (@"mySquare is a member of Rectangle class");
if ( [mySquare isMemberOfClass: [NSObject class]] == YES )
NSLog (@"mySquare is a member of NSObject class");
// isKindOf:
if ( [mySquare isKindOfClass: [Square class]] == YES )
NSLog (@"mySquare is a kind of Square");
if ( [mySquare isKindOfClass: [Rectangle class]] == YES )
NSLog (@"mySquare is a kind of Rectangle");
if ( [mySquare isKindOfClass: [NSObject class]] == YES )
NSLog (@"mySquare is a kind of NSObject");
// respondsTo:
if ( [mySquare respondsToSelector: @selector (setSide:)] == YES )
NSLog (@"mySquare responds to setSide: method");
if ( [mySquare respondsToSelector: @selector (setWidth:andHeight:)] == YES )
NSLog (@"mySquare responds to setWidth:andHeight: method");
if ( [Square respondsToSelector: @selector (alloc)] == YES )
NSLog (@"Square class responds to alloc method");
// instancesRespondTo:
if ([Rectangle instancesRespondToSelector: @selector (setSide:)] == YES)
NSLog (@"Instances of Rectangle respond to setSide: method");
if ([Square instancesRespondToSelector: @selector (setSide:)] == YES)
NSLog (@"Instances of Square respond to setSide: method");
if ([Square isSubclassOfClass: [Rectangle class]] == YES)
NSLog (@"Square is a subclass of a rectangle");
}
return 0;
}
//output
mySquare is a member of Square class
mySquare is a kind of Square
mySquare is a kind of Rectangle
mySquare is a kind of NSObject
mySquare responds to setSide: method
mySquare responds to setWidth:andHeight: method
Square class responds to alloc method
Instances of Square respond to setSide: method
Square is a subclass of a rectangle
4. @try @catch进行一场扑捉
#import <Foundation/Foundation.h>
int main (int argc, char * argv [])
{
@autoreleasepool {
NSArray *myArray = [NSArray array];
@try {
[myArray objectAtIndex: 2];
}
@catch (NSException *exception) {
NSLog (@"Caught %@%@", exception.name, exception.reason);
}
NSLog (@"Execution continues");
}
return 0;
}