OC basis

OC basis

IOS development interview essential skills chart.png

What are objects and what are the objects in OC?

An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects;

What is a class? What is a metaclass? What is the difference between class object and class, metaclass object and metaclass?

Class: it is the basis for realizing information encapsulation in object-oriented programming (OOP). Class is a user-defined reference data type, also known as class type. Each class contains a data description and a set of functions that manipulate data or deliver messages. An instance of a class is called an object
Metaclass: a class whose instance is a class;
Class object: class itself is also an object, so there are class objects; Class objects can be obtained through the ISA pointer of the instance object
Metaclass object: metaclass itself is also an object, so there are metaclass objects; Metaclass objects can be obtained through isa pointers to class objects
Distinguish between the two:

  • Class and metaclass are types in object-oriented programming
  • Class object and metaclass object are objects

What is classification?

Classification is also a class, and its underlying structure is slightly different from that of the class; The methods added to the classification will be merged into the method list (two-dimensional array) of the original class at run time
Classification is mostly used to extend classes; It is widely used in OC development

OC basis


What is a class extension?
Class extension: used to extend private properties and methods to classes

What is an array?
An array can be represented as a data structure that occupies a continuous memory space to store elements; There are two kinds of arrays in OC: variable and immutable; Variable arrays are optimizedRing buffer technologyImprove the performance of adding, deleting and modifying queries

What is a dictionary?
The dictionary stores data in the form of key value, and the underlying implementation is hash table; As the key of the dictionary, the OC object needs to comply with the nscopying protocol and implement the hash and isequal methods. For example, nsnumber, nsarray, nsdictionary, and custom OC objects can all be used as keys

What is a collection?
A collection is a data structure used to store data. The data stored internally is unordered, and others are the same as arrays

What are OC syntax?
The syntax in OC is a little syntax., the points here are generally converted to setter and getter method calls

What is method?
Method is method_ The structure of T is a description of a method:

struct method_t{
SEL name;              // Function name / method name
const char *types;// Code (return value type, parameter type)
IMP imp;                // Pointer to function (function address)

What is an introverted function?

  • Basic concepts of inline function
    In C + +, the concept of predefined macro is implemented by inline function, and the inline function itself is also a real function. Inline functions have all the behaviors of normal functions. The only difference is that inline functions expand like predefined macros in place, so there is no cost of function calls. Therefore, you should use inline functions instead of macros.

Add the inline keyword in front of a normal function (non member function) to make it an inline function. However, it must be noted that the function body and declaration must be combined, otherwise the compiler will treat it as an ordinary function.

inline void func(int a);

The above method has no effect. It is just a function declaration. It should be done as follows:

inline int func(int a){return ++;}

Note: the compiler will check whether the function parameter list is used correctly and return the value (make the necessary conversion).

These things cannot be done by the preprocessor.
Inline functions do take up space, but the advantage of inline functions over ordinary functions is that they save the overhead of stack pressing, jump and return when calling functions. We can understand that inline functions trade space for time.

  • Inline function inside class

    In order to define an inline function, you usually have to put an inline keyword before the function definition. However, it is not necessary to define inline functions inside a class. Any function defined inside a class automatically becomes an inline function.

What is a constructor?
Define a function with the same class name in a class. This function is the constructor

What are the principles of object-oriented design?
Single responsibility principleOpening and closing principleInterface isolation principleDependency Inversion PrincipleInternal Substitution PrincipleDimitri principle

  • Single responsibility principle
    A class is only responsible for one thing, calayer is only responsible for animation and view display, and uiview is only responsible for event transmission and event response
  • Opening and closing principle
    Closed for modification and open for extension; Consider the subsequent extension of the API instead of modifying it back and forth on the original basis
  • Interface isolation principle
    Use multi protocol to define the interface, rather than a cumbersome protocol; For example, delete, datesource
  • Dependency Inversion Principle
    Abstraction should not depend on concrete implementation, which depends on abstraction
  • Internal Substitution Principle
    The parent and child classes are seamlessly connected, and the original functions are not affected; For example: KVO, run out and leave no trace
  • Dimitri principle
    High cohesion, low coupling

What are the three characteristics of object-oriented language?
Encapsulation, inheritance, polymorphism

Inheritance system of OC

OC basis

OC’s inheritance system.png

Keyword usage criteria?
The arc environment modifies the OC object with strong, copy and weak, and modifies the basic data type with assign;
Static is used for static variables and const is used for constants

Common design patterns?

Design patterns are divided into four categories: structural pattern, creative pattern, behavioral pattern and software design principles

The commonly used structural modes are agent and decoration
Common creation modes include simple profit and factory
The commonly used behavior patterns are observer and publish subscribe

Proxy: it is a message passing method. A complete proxy model includes: delegate object, proxy object and protocol.

  • Please represent the trilogy:
    1 define agency agreement
    2 declare delegate object
    3 call proxy method
  • The trilogy of being someone else’s agent
    1. Compliance with the agreement
    2 set up agent
    3 implementation method

Decoration: dynamically add some additional responsibilities to a class; Category is the design pattern that realizes decoration; Category is a special class, through which you can add the interface and implementation of methods to the class;
Observer: includes notification and KVO
Simple interest: single: unique, example: instance; That is, the only instance, which is automatically released by the system from creation to program exit; Simple interest is often used as a common class;

Common simple interest classes in the system
Uiapplication (application instance class)
Nsnotificationcenter (message center class)
Nsfilemanager (file management class)
Nsuserdefaults (application settings)
Nsurlcache (request cache class)
Nshttpcookeiestorage (application cookie pool)

Factory mode: divided into simple factory mode, factory mode and abstract factory mode
Simple factory pattern: a simple factory pattern is a factory object that determines which product class instance to create. Simple factory pattern is the most simple and practical pattern in the factory pattern family, which can be understood as a special implementation of different factory patterns.
Factory pattern: it abstracts the specific products of the factory interface, and the application program calls different factories to create different product objects. (abstract product)
Abstract factory pattern: Based on the factory pattern, the factory is abstracted, and the application program calls the abstract factory to create different product objects. (abstract product + Abstract Factory)

Lazy loading: encapsulate the initialization logic by rewriting and call it directly when needed
Advantages of lazy loading

  • Relatively speaking, if the amount of code is not a lot, it is slightly more readable
  • Relatively speaking, the prevention is nil, which reduces the worries of safety inspection in subsequent use
  • Use properly to save memory resources
  • To some extent, it saves time in a certain period
  • Use properly, optimize performance and improve user experience
    Disadvantages of lazy loading
  • Too extensive use leads to poor readability
  • Improper use may cause dead circulation and crash
  • The amount of code increases (every time a lazy load is added, the code will increase by an average of 3-4 lines)

When to use lazy loading?

In general, lazy loading is not necessary. Lazy loading may not enhance readability and independence. Abuse will backfire on readability. In short, in logic, lazy loading can be considered if you don’t think it is necessary to load now, but it may be loaded in a later period of time

Producers and consumers:
In coding, we sometimes encounter the situation that one module generates data and another module processes data. Whether it is for coupling between modules, concurrent processing or uneven busy and idle, we will place a cache between the modules that generate and process data as a warehouse for production and processing data. The above model is the producer consumer model
Producer consumer


  • The intermediary model is also called the mediator model, which actually means the intermediary or mediator
  • Concept: mediator pattern, which encapsulates a series of object interactions with a mediator object. Mediators make objects do not need to explicitly refer to each other, so that they are loosely coupled, and their interaction can be changed independently
  • The UI navigationviewcontroller belongs to a mediator
  • Advantages and disadvantages of intermediary model
    The mediator model is easy to be applied in the system and misused in the system. When there are many to many interactive complex object groups in the system, don’t rush to use the mediator mode, but first reflect on whether your design on the system is reasonable.
    The advantage is centralized control, which reduces the coupling between objects. The disadvantage is that it is too focused
  • Application scenario
    Although the interaction between objects is clearly defined and very complex, a group of objects are interdependent and difficult to understand.
    Because objects refer to and communicate with many other objects, it is difficult to reuse objects.
    You want to customize the logic or behavior distributed in multiple classes without generating too many subclasses

Publish subscribe mode

In fact, there is no publish subscribe mode in the basic design mode. As mentioned above, it is just a nickname of observer mode. However, after the precipitation of time, it seems that it has become strong and independent of the observer mode, becoming another different design mode.
In the current publish subscribe mode, the message sender called publisher will not send the message directly to the subscriber, which means that the publisher and subscriber do not know each other’s existence. There is a third component between publishers and subscribers, called message broker or scheduling center or middleware. It maintains the relationship between publishers and subscribers, filters all incoming messages from publishers and distributes them to subscribers accordingly.

For example, if you pay attention to a on your microblog and many other people pay attention to a, then when a releases a dynamic, the microblog will push this dynamic for you. A is the publisher, you are the subscriber, and microblog is the dispatching center. You and a do not have direct information exchange. They are all coordinated through microblog (your attention, a’s release dynamics)

What is the difference between observer mode and publish subscribe mode?

Observer mode: the observer directly subscribes to the subject. When the subject is activated, the fire event in the observer will be triggered.

Publish and subscribe mode: the subscriber registers the event he wants to subscribe to to the scheduling center (topic). When the publisher publishes the event (publish topic) to the scheduling center, that is, when the event is triggered, the scheduling center uniformly dispatches the processing code that the subscriber registers to the scheduling center. It is common to do it by protocol

  • Is the observer mode a publish subscribe mode

Online answers to this question are polarized. Some think that the publish and subscribe mode is the observer mode, and others think that the observer mode is really different from the publish and subscribe mode.

In fact, I don’t know whether the publish / subscribe mode is the observer mode, just as I don’t know whether the key to distinguish the mode is the design intention or the design structure (concept). Although the book JavaScript Design Patterns and development practice says that the key to distinguish the mode is the intention rather than the structure.

If the mode is distinguished by structure, the publish subscribe mode has one more middleware subscriber than the observer mode, so the publish subscribe mode is different from the observer mode; If patterns are distinguished by intention, they all realize a one to many dependency between objects. When the state of an object changes, all objects that depend on it will be notified and updated automatically. Then they are the same pattern. The publish subscribe pattern is an optimization and upgrade based on the observer pattern.

However, whether they are the same design pattern or not, their implementation methods are different. When we use them, we should judge which one to choose according to the scenario


  • Block is an OC object that encapsulates function calls and function call environments. There are three types of blocks: nsglobalblock, nsstackblock, nsmallocblock; They all inherit from nsblock, and nsblock inherits from nsobject;
  • Circular reference should be paid attention to when using block; Generally, strong and weak references are required__ Block to solve the problem
  • When a block is declared as an attribute, it needs to be modified with copy or strong; Because block is initially allocated in stack space, memory is managed by the system; However, generally, using a block needs to be used at a certain time during runtime, so developers need to manage the memory of the block by themselves. Using copy and strong decoration will copy the memory of the block to the heap space, so as to achieve the purpose of managing memory by themselves

Why is the initial memory of block allocated in stack space?
Block can be used in two ways:local variabletypedefstatement
The memory requested by local variables must be in stack space

The nature of the object?
The essence of object is structure;
Memory allocation principle: it is in 16 bytes and followsMemory alignment principleRequest memory space from heap memory

Isa pointer?
Isa pointer is the first member variable of OC object; ISA is a consortium structure, which stores data through bit domain;
The most important function of ISA is to send messages;

Bit domain macro definition (real machine environment arm64)
# if __arm64__
#   define ISA_MASK        0x0000000ffffffff8ULL
#   define ISA_MAGIC_MASK  0x000003f000000001ULL
#   define ISA_MAGIC_VALUE 0x000001a000000001ULL
#   define ISA_BITFIELD                                                      \
     uintptr_ t nonpointer        : 1;  Take 1 bit of binary to store\
     uintptr_t has_assoc         : 1;                                       \
     uintptr_t has_cxx_dtor      : 1;                                       \
     uintptr_t shiftcls          : 33; /*MACH_VM_MAX_ADDRESS 0x1000000000*/ \
     uintptr_t magic             : 6;                                       \
     uintptr_t weakly_referenced : 1;                                       \
     uintptr_t deallocating      : 1;                                       \
     uintptr_t has_sidetable_rc  : 1;                                       \
     uintptr_t extra_rc          : 19
#   define RC_ONE   (1ULL<<45)
#   define RC_HALF  (1ULL<<18)

OC’s memory management principles?
Memory management in OC is realized through reference count management. When the reference count of an object is 0, it will enter the release process; Arc uses the llvm compiler to dynamically add memory management code in the right place to help developers manage memory, and manages the weak reference table modified by weak through runtime; It basically realizes that developers can develop without paying attention to memory problems;

  • You should pay attention to circular reference when using block and timer
  • When declaring properties, you need to pay attention to the use of strong and weak references


Namelymultithreading, refers to the technology of implementing multiple threads to execute concurrently from software or hardware.
Computers with multithreading capability can execute more than one thread at the same time because of hardware support, so as to improve the overall processing performance. Systems with this capability include symmetric multiprocessors, multi-core processors, and chip level multithreading or simultaneous multithreading processors. In a program, these independently running program segments are called “threads”, and the concept of programming using them is called “multithreading”.
The scheduling principle of multithreading can be considered as follows: time slice rotation scheduling algorithm, each thread will allocate a time slice, and then everyone will do the task in turn. When multithreading is executed, it will quickly switch the time slice to complete the execution of multithreaded tasks; In fact, the operating system implements processes and threads according to this scheduling logic

What are programs, processes, threads, routines, and coroutines?

  • Program: the full name of computer program is a group of instructions that can be recognized and executed by the computer, also known as computer software
    It refers to a coded instruction sequence that can be executed by a computer or other device with information processing ability in order to obtain a certain result, which is written in some programming languages, such as C, C + +, OC, etc; It runs onelectronic computerupper

  • Process: a running activity of a computer program on a data set; It is the basic unit for independent operation, independent resource allocation and independent scheduling; It is the basis of operating system architecture

In the contemporary computer architecture of thread oriented design, process is the container of thread. Program is the description of instructions, data and their organizational form, and process is the entity of program

  • Thread: thread is the smallest unit of computer scheduling, which is used to handle different tasks;

  • Routine: that is, a function. A function can be regarded as a routine

  • Co process: the technical solution of using single thread to execute multi tasks. In terms of performance, avoiding inter thread switching is better than thread scheduling; It is a smaller split of threads, also known as “micro thread”, which is a lightweight thread that users are too busy with;
    Difference between and thread:
    Threads are system level, and they are scheduled by the operating system; At the same time, it is the smallest unit that can be scheduled;
    The cooperation process is program level, which is scheduled by the programmer according to the needs
    Subroutines: Functions
    There are many subroutines in a thread. During the execution of the subroutine, other subroutines can be interrupted to execute other subroutines, and other subroutines can also be interrupted to continue to execute the previous subroutine. This process is called coprocess. That is, in the same thread, a piece of code will be interrupted during execution, then jump to execute other code, and then continue to execute where it was interrupted, similar to the yield operation

Instance lifecycle?

  • alloc、new、copy、mutableCopy
  • Reference count change
  • Reference count is 0
  • dealloc

Controller lifecycle?
Declaration period of the controller

Responder chain?

Complete touch event transmission process

Recommended Today

Application of analytic proxy pattern in Ruby design pattern development

proxy patternProxy proxy mode is a structural typeDesign pattern, the main problem to be solved is the problem caused by directly accessing objects. For example, the object to be accessed is on a remote machine. In an object-oriented system, direct access to some objects will bring a lot of trouble to users or system structure […]