iOS develops a variety of bottom-up implementations-interview essentials!

Source: Internet
Author: User
Tags gcd

iOS Development common technology bottom-up implementation (thin overview)

This chapter will be a summary of the implementation of iOS development technology, in fact, on the implementation of various underlying iOS development, online related articles more than a few, but not very good, I do not have confidence that I can do better than they do, because after all, each person specialized research things are not the same, this article is mainly for three types of users!

    1. Experienced iOS developers have done a lot of research on the ground floor, but none of the systems have been organized, or clearly expressed.
    2. iOS development beginner, did not specifically study the underlying or related source of the beginner, but not very recommended to see the beginning, because if you do not have a little touch, see also do not understand, or see also white, at most is to leave an impression in the brain, for beginners, remember can not backrest or understand, and carefully study each technology point, and then slowly dig deeper.
    3. iOS Development Unemployed Programmer (interview) dedicated, regardless of whether you have contact with iOS development related to the underlying, as long as you are ready to find a job of the programmer, I believe you see absolutely useful, but not positive you really understand, so I hope this is only temporary for you, The follow-up will take a lot of time to specialized research to go farther on this road, or you will always be a yard farm!

Well, no more nonsense, let's start ...

System Chapter
    • Memory management
    • Runtime
Event Chapter
    • Event delivery
    • Incident response
Code article
    • Block
    • __block
Actual combat
    • KVO
    • KVC
Senior
    • GCD
Full stack
    • Jspatch
    • React Native
Necessary articles
    • Multithreading
    • Internet
    • Data persistence
General articles
    • Array
    • Dictionary
    • Collection
#写在最后系统篇内存管理
    • Golden Rule

      • If an object uses Alloc,[mutable] Copy,retain, then you must use the appropriate release or autonrelease

Mrc:

 手动管理内存(retain, release, autorelease,不多说) 持有对象,retain +1 ,引用计数加1, 释放对象:release -1, 引用计数减1,当引用计数为0时,会自动释放内存.  autorelease对象内存的管理放到autoreleasepool中, 当pool drain时,回收内存. (这是基于 objective-c的运行时特性和垃圾回收机制)

ARC:

 手动管理内存, 这是xcode4.x版本的特性,(4.1及以前没有,我从4.6开始的), 原理是:在编译代码的时候为你自动在合适的位置插入release 和 autorelease, (运行时处理垃圾回收就如何MRC一样).

Summary: The arc mechanism has the same efficiency as MRC, and ARC supports the use of arc by partially optimizing and maintaining reference counting in the most appropriate place.

Rules

Rules:

    • 1, the Objective-c class implements the reference counter, the object knows its current number of references

    • 2, the initial object counter is 1

    • 3, if you need to reference the object, you can send an retain message to the object, so that the object's counter is added 1

    • 4, when you do not need to reference the object, you can send the release message to the object, so that the object counter is reduced by 1

    • 5, when the counter is reduced to 0, automatically call the object's Dealloc function, the object will free memory

    • 6. Objects with counter 0 can no longer use release and other methods

Runtime

A set of pure low-level C language library usually we write the OC code will be turned into runtime to execute

Characteristics:

动态类型:程序直到执行时才能确定所属的类。动态绑定:程序直到执行时才能确定实际要调用的方法。动态加载:根据需求加载所需要的资源

Runtime message mechanism

The class of obj is first found through the ISA pointer of obj.

    • First check whether this selector is to be ignored. For example, Mac OS X was developed, and garbage collection ignores retain,release of these functions.
    • Detecting whether the target of this selector is NIL,OBJC allows us to execute any method on a nil object without Crash, because the runtime is ignored.
    • If the above two steps are passed, then start looking for the implementation of this class IMP,
    • In class, first go to the cache through the SEL to find the corresponding function method, found to execute the corresponding implementation.
    • If the cache is not found, then go to MethodList to find the implementation of the corresponding.
    • If not found in MethodList, take superclass (repeat the two steps above) until the root class is found.
    • If any of these can be found, the method is added to the cache to facilitate the next lookup, and the function pointer in method jumps to the corresponding function to execute.
    • If none of the above is found, message forwarding will begin

Message forwarding

    • 1. Dynamic method parsing: Sends a resolveinstancemethod: signal to the current class to check whether a method has been added to the class dynamically. (Search for confusion: @dynamic)
    • 2. Fast message forwarding: Check whether the class implements the Forwardingtargetforselector: method, or call this method if it is implemented. If the method returns a value object that is non-nil or non-self, resend the message to the returned object.
    • 3. Standard message forwarding: Runtime sends Methodsignatureforselector: Message gets selector corresponding method signature. The return value is non-null by forwardinvocation: Forwards the message, and the return value is null to send doesnotrecognizeselector: message, program crashes exit

The summary is: When a function is not found, OC provides three ways to remedy:

    • 1, call Resolveinstancemethod give the opportunity to let the class add this implementation of this function
    • 2. Call Forwardingtargetforselector to allow other objects to execute this function
    • 3. Call Forwardinvocation (function executor) to flexibly execute the target function in other form. If none of the calls Doesnotrecognizeselector throws an exception.
How does an event application find the most appropriate control to handle an event?
1.首先判断主窗口(keyWindow)自己是否能接受触摸事件2.判断触摸点是否在自己身上3.子控件数组中从后往前遍历子控件,重复前面的两个步骤(所谓从后往前遍历子控件,就是首先查找子控件数组中最后一个元素,然后执行1、2步骤)4.view,比如叫做fitView,那么会把这个事件交给这个fitView,再遍历这个fitView的子控件,直至没有更合适的view为止。5.如果没有符合条件的子控件,那么就认为自己最合适处理这个事件,也就是自己是最合适的view
Differences in the delivery and response of events:
    • The delivery of an event is from top to bottom (parent control to child control), and the response of the event is from bottom to top (passing up the responder chain: child control to parent control.)
Event delivery process for an incident response responder chain:
1>如果当前view是控制器的view,那么控制器就是上一个响应者,事件就传递给控制器;如果当前view不是控制器的view,那么父视图就是当前view的上一个响应者,事件就传递给它的父视图2>在视图层次结构的最顶级视图,如果也不能处理收到的事件或消息,则其将事件或消息传递给window对象进行处理3>如果window对象也不处理,则其将事件或消息传递给UIApplication对象4>如果UIApplication也不能处理该事件或消息,则将其丢弃
The entire process of event delivery event handling is summarized as follows:
  1.触摸屏幕产生触摸事件后,触摸事件会被添加到由UIApplication管理的事件队列中(即,首先接收到事件的是UIApplication)。  2.UIApplication会从事件队列中取出最前面的事件,把事件传递给应用程序的主窗口(keyWindow)。  3.主窗口会在视图层次结构中找到一个最合适的视图来处理触摸事件。(至此,第一步已完成)  4.最合适的view会调用自己的touches方法处理事件  5.touches默认做法是把事件顺着响应者链条向上抛。
The underlying implementation of the code block

One word:

栈地址和对地址值的拷贝block就是一个里面存储了指向函数体中包含定义block时的代码块的函数指针,以及block外部上下文变量等信息的结构体。

The block structure contains the ISA pointer, which proves that block is actually an object and has all the functions of a generic object. This ISA pointer is initialized to the address of the Nsconcretestackblock or Nsconcreteglobalblock class. In the case where arc is not turned on, if the block contains local variables, ISA is initialized to the former, otherwise it is initialized to the latter. When arc is turned on, ISA is initialized to Nsconcretemallocblock if the block contains local variables , otherwise it is initialized to Nsconcreteglobalblock. Invoke is a function pointer that points to the address where the block is converted into a function. The final imported variables part is the external local variables that the block needs to access, and they will be copied to the block when they are compiled, so that the block becomes a closed packet.

__block Bottom-level implementation
一句话:传值 和传址

Block Print C + + source can see The block_byref_a_0 struct, which contains the ISA pointer, is also an object that is used to wrap the local variable A. When the block is copied to the heap,person Test_block_impl_0 's Copy helper, person Test_block_copy_0, will __block_byref_a_ 0 is copied to the heap, so even if the local variable is destroyed, the block can still operate on the local variables in the heap.

这样做是为了保证操作的值始终是堆中的拷贝,而不是栈中的值。(处理在局部变量所在栈还没销毁,就调用block来改变局部变量值的情况,如果没有__forwarding指针,则修改无效)
Actual Combat article KVO/KVC

VC/KVO is an implementation of the observer pattern, which is defined as part of the underlying framework in cocoa, in the form of nskeyvaluecoding/nskeyvalueobserving informal protocol implemented by the source NSObject class of things. From an agreement standpoint, KVC/KVO essentially defines a set of methods that let us follow and implement. Of course, the KVC/KVO implementation of the fundamental is objective-c dynamic and runtime, which in the later part of the principle will be described in detail. In addition, the KVC/KVO mechanism is inseparable from the implementation of accessor methods, which are explained in the following article.

1, KVC Introduction

全称是Key-value coding,翻译成键值编码。顾名思义,在某种程度上跟map的关系匪浅。它提供了一种使用字符串而不是访问器方法去访问一个对象实例变量的机制。

2, KVO Introduction

全称是Key-value observing,翻译成键值观察。提供了一种当其它对象属性被修改的时候能通知当前对象的机制。再MVC大行其道的Cocoa中,KVO机制很适合实现model和controller类之间的通讯。
KVO implementation (based on kvc-runtime)

When an object of a class is first observed, a derived class of that class is dynamically created at runtime, overriding the setter method of any observed attribute in the base class in this derived class.

派生类在被重写的 setter 方法实现真正的通知机制,就如前面手动实现键值观察那样。这么做是基于设置属性会调用 setter 方法,而通过重写就获得了 KVO 需要的通知机制。当然前提是要通过遵循 KVO 的属性设置方式来变更属性值,如果仅是直接修改属性对应的成员变量,是无法实现 KVO 的。同时派生类还重写了 class 方法以“欺骗”外部调用者它就是起初的那个类。然后系统将这个对象的 isa 指针指向这个新诞生的派生类,因此这个对象就成为该派生类的对象了,因而在该对象上对 setter 的调用就会调用重写的 setter,从而激活键值通知机制。此外,派生类还重写了 dealloc 方法来释放资源

The ISA pointer is actually the class's meta-class, and if the previous class name is: Person, then the class name after the runtime changes to: Nskvonotifying_person. The new Nskvonotifying_person class overrides the following method: Adds a set method for the listener's properties, CLASS,DEALLOC,_ISKVOA

The underlying implementation of KVC

KVC used a isa-swizzling technique. Isa-swizzling is the type-mixed pointer mechanism. KVC mainly through the isa-swizzling, to achieve its internal search and positioning. The ISA pointer, as its name implies, (that is, the meaning of the is a kind of), points to the class that maintains the sub-published object. This sub-publication actually contains pointers to the methods in the implementation class, and other data.

When an object is called SetValue, the

    • (1) The environment parameters needed to run the method are first found according to the method name.
    • (2) He will combine the environment parameters from his own Isa pointer to find the specific method implemented by the interface.
    • (3) The specific method can be directly found.
Advanced GCD Bottom-level implementation

How does the GCD interior come true?

    • 1 The core of iOS and OS X is the XNU kernel, GCD is implemented based on the Xun kernel
    • 2 GCD APIs are all in the Libdispatch library
    • The underlying implementations of the 3 gcd are mainly dispatch Queue and dispatch Source

      • Dispatch Queue: Managing block operations
      • Dispatch Source: Handling events (such as inter-thread communication)

The difference between Nsoperationqueue and GCD and a similar place

    • 1 GCD is a pure C language API, Nsoperationqueue is based on the GCD version of OC Package
    • 2 GCD only supports FIFO queue, nsoperationqueue can easily adjust execution order setting maximum concurrent quantity
    • 3 Nsoperationqueue can easily set dependencies between operation, and GCD need to write a lot of code
    • 4 Nsoperationqueue Support KVO, can monitor whether operation is executing (is Executed), whether the end (is finished), whether cancel (is Canceld);
    • 5 GCD is executed faster than nsoperationqueue
Full stack Jspatch bottom level implementation

Jspatch can do through JS call and rewrite OC method The most fundamental reason is that objective-c is a dynamic language, OC on all methods of the call/class generation through the Objective-c runtime at runtime, we can be reflected by the class name/method name of the corresponding class and methods:

Class class = NSClassFromString("UIViewController");id viewController = [[class alloc] init];SEL selector = NSSelectorFromString("viewDidLoad");[viewController performSelector:selector];

You can also replace the method of a class with a new implementation:

static void newViewDidLoad(id slf, SEL sel) {}class_replaceMethod(class, selector, newViewDidLoad, @"");

You can also register a new class to add a method to the class:

Class cls = objc_allocateClassPair(superCls, "JPObject", 0);objc_registerClassPair(cls);class_addMethod(cls, selector, implement, typedesc);

For the Objective-c object model and the principle of dynamic message delivery has been a lot of articles elaborated very detailed, here is not elaborated in detail. Theoretically you can call any OC method at run time through the class name/method name, replacing the implementation of any class and adding any new classes. So the basic principle of Jspatch is: JS pass string to Oc,oc through the Runtime interface call and replace OC method. This is the most basic principle, the actual implementation of the process there are a lot of strange to play, and then see how the specific implementation.

Summarize:

Use JS to take advantage of the dynamic characteristics of OC to execute the code we want to execute

React Native

RN main communication is between Java and JS, the usual JSX code we write will eventually call to the original view. Previous blog We also learned that to create a new native module needs to write a module in the Java layer and JS layer, respectively

Characteristics:

    • Application logic can be written using JavaScript based on React native, and the UI can be kept entirely native. In this way, there is no need to make a common compromise on the HTML5 UI;

    • React introduces a unique, slightly aggressive but highly available solution to build the user interface. To make a long story short, the UI of the app is simply expressed by a function based on the current state of the application.

RN Total is divided into three tiers, Java layer, C + + layer, JS layer

    • Java layer: The Java layer is the app native code that executes the JS code by starting the C + + layer's JavaScript parser javascriptcore to build the native UI, and so on. Java layer relies on a number of excellent open source libraries, in the image processing using fresco, network communications using Okhttp,json Analytic tool with Jackson, animation library with Nineoldandroids, etc., in the Java layer native functions are encapsulated as module, such as toast and log.
    • C + + layer: The C + + layer is the most important encapsulation of javascriptcore, it is a new support ES6 WebKit. Bridge connects the communication between Java and JS. Parsing the JS file is done through Jscexectutor.
    • JS Layer: The main processing event distribution and UI Layout, usually developed the most commonly used. General JSX to write business code, through Flexbox to implement the layout. Do not rely on DOM. Because react has a DOM diff algorithm, it is very efficient. Communication mechanisms

In the Java layer and JS Layer Bridge has the same module configuration table, Java and JS communication with each other, by the Moduleid,methodid in the configuration table converted to JSON data in the form of the transfer to the C + + layer, C + + layer to the JS layer, Through the JS layer of the Module configuration table to find the corresponding method to execute, if there is callback, then back to the Java layer. Here is just about the introduction.

Summarize:

  • When the program starts, it first calls Reactactivity's OnCreate function, and we will create a Reactinstancemanagerimpl object. Open the door to the whole RN world through Reactrootview's Startreactapplication method.
  • In this method, we will create the Reactcontext through a asynctask.
  • In the creation of Reactcontext, we inject ourselves and coremodulespackage through processpackage methods to inject each modules into the corresponding registry. Finally, the Nativemodule and Jsmodule registries are transferred to the JS layer via JNI through the Reactbridge in Catalystinstanceimpl.
  • When Java calls JS, it is stored in the registry class Javascriptmoduleregistry when Reactapplicationcontext is created, and the proxy instance is generated by the dynamic proxy. All communication requests to JavaScript are processed uniformly in the proxy interception class Javascriptmoduleinvocationhandler.
  • Jscexecutor encapsulates all communication requests from the Java layer into JavaScript execution statements.
  • Then in the JS layer in the MessageQueue match ModuleID and Methodid. Locate the calling module.
  • If the JS layer calls the Java layer, JS will eventually call the _nativecall method, by Flushedqueue this. The queue is returned to Bridger.
  • The C + + layer invokes the Oncallnativemodules method of the Platformbridgecallback object, executes the Makejavacall method, and finally calls the Java layer method through Env->callvoidmethod.
  • The call method of the Java layer nativemodulesreactcallback is called, which matches the Nativemodule object that needs to be executed by ModuleID from the nativemodule mapping table that is stored inside it. The methodid is then matched to the method to be called. The method of executing nativemodule by means of invoke reflection.
Mandatory multi-threaded network data Persistence General Purpose array Dictionary collection

iOS develops a variety of bottom-up implementations-interview essentials!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.