Objective-C程序设计第九章---多态、动态类型和动态绑定

这一章主要讲述了多态的概念,怎样实施动态绑定

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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值