Objective-C为什么是门动态语言

参考文档:developer.apple.com/library/con…

  • 动态类型 id类型,编译器在编译的时候是不知道这个变量是什么类型的(id修饰)

Type checking is useful, but there are times when it can interfere with the benefits you get from polymorphism, especially if the type of every object must be known to the compiler.

虽然类型检查不错,但是有时候这种机制会干扰我从多态性中获得好处,特别是编译器必须知道是什么类型的时候。

Suppose, for example, that you want to send an object a message to perform the start method. Like other data elements, the object is represented by a variable. If the variable’s type (its class) must be known at compile time, it would be impossible to let runtime factors influence the decision about what kind of object should be assigned to the variable. If the class of the variable is fixed in source code, so is the version of start that the message invokes.

例如:你想向对象发送消息以执行start方法,如果编译器知道这个变量的类(类型),那么就只能调用对应的start方法,酱紫就少了运行时的因素影响,即动态性。如果这个对象的类在源代码中是固定的,那么调用的start方法也是固定的了

If, on the other hand, it’s possible to wait until runtime to discover the class of the variable, any kind of object could be assigned to it. Depending on the class of the receiver, the start message might invoke different versions of the method and produce very different results.

如果可以到运行时才来确定这个对象是哪个类的,然后根据这个类来调用对应的start方法,那么这就有很多不同的结果了

Dynamic typing thus gives substance to dynamic binding (discussed next). But it does more than that. It permits associations between objects to be determined at runtime, rather than forcing them to be encoded in a static design. For example, a message could pass an object as a parameter without declaring exactly what kind of object it is—that is, without declaring its class. The message receiver might then send its own messages to the object, again without ever caring about what kind of object it is. Because the receiver uses the passed object to do some of its work, it is in a sense customized by an object of indeterminate type (indeterminate in source code, that is, not at runtime).

动态类型为动态绑定提供了实现基础

  • 动态绑定

在C语言中,你可以声明字符串相关函数

int strcmp(const char *, const char *);   /* case sensitive */
int strcasecmp(const char *, const char *); /*case insensitive*/
复制代码

也可以用指针指向函数

int (* compare)(const char *, const char *);

复制代码

你可以等到运行时才来确定这个compare指针指向哪个函数

如果(** argv =='i')
    compare = strcasecmp;
其他
    compare = strcmp;
复制代码

并通过指针调用函数

if(比较(s1,s2))
    ...
复制代码

动态绑定就是延迟了在程序运行之前,确定要执行哪种方法的决定。

如果没有动态类型,就是一开始编译器就知道这个对象是哪个类,那么也就没有动态绑定,因为编译器既然知道这个对象是哪个类了,其实也就知道我运行起来会去调用谁了,就没了动态性了

  • 动态加载

oc中用runtime在运行时动态的创建一个类,这就是动态加载了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值