OC动态语言特性

701 阅读3分钟

根据苹果开发文档

Objective-C adds the following syntax and features to ANSI C:
Objective-C向ANSI C中添加了以下语法和特性:
…
Static and `dynamic typing`
静态和动态类型
…

体现在运行时


In addition to providing most of the abstractions and mechanisms found in other object-
oriented languages, Objective-C is a very dynamic language, and that dynamism is its 
greatest advantage. It is dynamic in that it permits an app’s behavior to be determined 
when it is running (that is, `at runtime`) rather than being fixed when the app is built. 
Thus the dynamism of Objective-C frees a program from constraints imposed when it’s 
compiled and linked; instead it shifts much of the responsibility for symbol resolution 
to runtime, when the user is in control.

除了提供其他面向对象语言中的大多数抽象和机制外,Objective-C是一种非常动态的语言,这种动态性是它的最大
优势。它是动态的,因为它允许应用程序的行为在运行时(即`运行时`)被确定,而不是在应用程序构建时被修复。因此,
Objective-C的动态性将程序从编译和链接时强加的约束中解放出来;相反,它将符号解析的大部分责任转移到运行
时,此时用户处于控制之下。

支持动态类型

Objective-C supports `dynamic typing` for variables containing objects, but it also 
supports static typing. Statically typed variables include the class name in the 
variable type declaration. Dynamically typed variables use the type id for the object 
instead. You find dynamically typed variables used in certain situations. For example, 
a collection object such as an array (where the exact types of the contained objects 
may be unknown) might use dynamically typed variables. Such variables provide 
tremendous flexibility and allow for greater dynamism in Objective-C programs.

Objective-C支持包含对象的变量的动态类型,但也支持静态类型。静态类型变量在变量类型声明中包含类名。动态
类型变量使用对象的类型id代替。您会发现在某些情况下使用动态类型的变量。例如,数组等集合对象(其中所包含对
象的确切类型可能未知)可能使用动态类型变量。这些变量在Objective-C程序中提供了极大的灵活性和更大的动态
性。

这个例子展示了静态和动态类型的变量声明:

MyClass *myObject1;  // Static typing
id       myObject2;  // Dynamic typing

值得注意的是,由于id类型在运行时才确定类型,所以在不能使用点语法

This syntax is simply a different way to write [myObject1 setTheArray:aNewArray];. 
You cannot use a reference to a dynamically typed object (type of id) in a dot-notation 
expression.
点语法只是编写`[myObject1 setTheArray:aNewArray]`的一种不同方式。不能在点符号表达式中使用对动态
类型对象`myObject2(id类型)`的引用。

一.动态类型 Dynamic typing

就是上面提及的在运行时才决定真正的类型。

二.动态绑定 Dynamic binding

静态绑定,编译器在编译时会进行类型检查,一旦出现类型方法不一致匹配失败。OC和C#类似,动态绑定把方法绑定推迟到了运行时,最明显的例子就是运行时可以实现方法的交换。根据百度百科资料,动态绑定指的是将一个过程调用与相应代码链接起来的行为。动态绑定是指与给定的过程调用相关联的代码只有在运行期才可知的一种绑定,它是多态实现的具体形式。

三. 动态加载 Dynamic loading

运行时加载新类,在运行时创建一个新类.

参考资料

苹果开发文档
Objtive-C 动态语言的理解
oc语言的特性 动态类型识别,动态绑定,动态加载
面向对象