zoukankan      html  css  js  c++  java
  • runtime

    消息的处理就是需要先确定实际执行的方法然后跳转过去并执行

    Objective-C对象的内存空间仅分配在“堆空间”(heap space)中,肯定是不会分配在“栈”(stack)上

    因此,我们可以看出,“栈”其实是无法实施“引用计数”机制的,Objective-C否定使用“栈”存储对象的设想。

    Objective-C这一“任性”的设计,也使得对象嵌套(一个对象作为另一个对象的成员变量)时,对象基于引用计数机制,其成员变量也必须递归地遵循引用计数机制。因为成员变量实际都是一枚枚对象指针,很可能是与其它对象共享同一个对象(指针都指向同一块内存),引用计数机制正是适合用于支持这种“共享”内存的管理。需要特别说明,如果可以像C++那样创建一个对象变量做成员变量,那么该成员变量会被存储在该对象所在的一块连续内存块,该对象销毁时能够自动把成员变量的占有的内存块全部释放收回,这与引用计数的机制并不太符合,所以,在Objective-C中对象变量不被支持也进一步得到理解。

    当对象查询不到相关的方法,消息无法正确回应时,还会启动“消息转发”机制。是的,在支持“动态增加和替换”的方法列表之外,我们还能够提供其它的正常响应方式。消息转发还分为几个阶段,第一,先询问receiver或者说是它所属的类,看其是否能动态添加方法,以处理当前这个“未知选择子”(unkonwn selector),这叫做“动态方法解析”(dynamic method resolution),Runtime会通过回调一个类方法来寻求动态添加方法的支持。如果Runtime完成动态添加方法的询问之后,receiver仍然无法正常响应,则Runtime会继续向receiver询问是否有其它对象即其它receiver能处理这条消息,若返回能够处理的对象,Runtime会把消息转给返回的对象,消息转发流程也就结束。若无对象返回,Runtime会把消息有关的全部细节都封装到NSInvocation对象中,再给receiver最后一次机会,令其设法解决当前还未处理的这条消息。消息转发的流程可以归纳到以下图表:

    http://www.cocoachina.com/ios/20150907/13336.html


    When a message is sent to an object, the messaging function follows the object’s isa pointer to the class structure where it looks up the method selector in the dispatch table. If it can’t find the selector there, objc_msgSend follows the pointer to the superclass and tries to find the selector in its dispatch table. Successive failures cause objc_msgSend to climb the class hierarchy until it reaches the NSObject class. Once it locates the selector, the function calls the method entered in the table and passes it the receiving object’s data structure.


    The second chance offered by a forwardInvocation: message provides a less ad hoc solution to this problem, and one that’s dynamic rather than static. It works like this: When an object can’t respond to a message because it doesn’t have a method matching the selector in the message, the runtime system informs the object by sending it a forwardInvocation: message. Every object inherits a forwardInvocation: method from the NSObject class. However, NSObject’s version of the method simply invokes doesNotRecognizeSelector:. By overriding NSObject’s version and implementing your own, you can take advantage of the opportunity that the forwardInvocation: message provides to forward messages to other objects.


  • 相关阅读:
    Java 打印HelloKitty
    Android四大组件:BroadcastReceiver 介绍
    详解 Handler 消息处理机制(附自整理超全 Q&A)
    垃圾回收机制 —— 整理介绍
    四种引用类型 —— 软引用与弱引用的应用
    线程池 —— 使用介绍
    倒计时器 CountDownTimer
    屏幕旋转时 Activity 的生命周期 —— 测试与结论
    arcengine Objects in this class cannot be updated outside an edit session(不能在编辑会话之外更新此类对象)解决办法
    基于rtmp+nginx 、vlc实现FFmpeg推流与wpf端拉流
  • 原文地址:https://www.cnblogs.com/studyNT/p/4955386.html
Copyright © 2011-2022 走看看