您的位置:首页 > 移动开发 > Objective-C

Programming in Objective C学习笔记03——多态、动态绑定和动态类型

2016-03-10 18:50 417 查看

PART I —— The Objective-C Language (ch.9)

Polymorphism 多态

同名的method,不同的class

运行时系统总是携带有关“对象属于哪个类”的信息 → This enables it to make key decisions at runtime instead of at compile time.

Each class definition encapsulates the code needed to respond to that particular method, and this makes it independent of the other class definitions.

Dynamic Binding and the id Type 动态绑定和id类型(即dynamic typing)

During execution of the program, before the system sends the message to id type variable, it first checks the class of the object stored inside the variable.

When combined with polymorphism, dynamic binding and dynamic typing enable you to easily write code that can send the same message to objects from different classes.

id类型的某些错误(比如使用错误的方法),在编译时不会被发现,只有在运行时会导致程序崩溃

对id类型的对象不能使用点操作符(
.
),编译器会报错

id类型作参数类型和返回值类型

若某方法在一个class中使用基本数据类型作参数类型而在另一个class中使用对象作参数类型(返回值同理),当用id类型调用此方法(或传参)时,编译器会生成错误错误代码

但是若方法的参数类型(返回值类型)是不同class的对象,则用id类型时不会产生编译错误(原因:传递的时指向对象的引用)

Static typing 静态类型:定义一个变量用于存放特定class的对象

尽量使用static typing → ①便于编译器检查错误;②提高代码的可读性

NSObject类提供一些用于处理Dynamic types的方法

class-object(类对象)——generated with the class method(方法名为class)

selector 是 SEL类型的值——由@selector指令产生

根据class名或另一个对象生成类对象(class object),可以向它发送class消息

[class名 class];


[对象名 class];   //可以获知对象所属的class


@selector:生成SEL类型的值,可以保存到SEL类型的变量中

@selector(方法名)   //方法如果有参数,冒号要写,参数不用写


判断id类型对象能否执行某方法
respondsToSelector:@selector(…)


使用@try处理异常

Good programming practice dictate that you try to anticipate problems that can occur in your program.

syntax:

@try block中运行正常,程序继续;若出现异常,则进入@catch block中执行语句,通常为记录错误信息,清理,结束程序

@finally block :无论@try block中是否抛出异常(exception)都要执行的code,比如release/clean up resources like open sockets, open files, database locks, semaphore locks, and so on.

The finally block is the last, best chance to exit cleaning from an application that is about to crash.

@throw:
@throw;
enables you to throw your own exception. → 让系统完成其余工作

可以抛出特定异常,或者处理@catch block中的异常

完成异常处理后(比如清理)

可以使用多个@catch blocks处理不同类型的异常

It’s better to

test for errors before they occur rather than catch them

test for an error in a method and return some value as an error indicator than to throw an exception

If you catch an exception, you only do so with the intention of cleaning up and terminating your application.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  objective-c