The answers to the following questions are from an article I wrote in the past, which were asked by the interviewer in the interview. Hope to help you. Please contact me if you have any questions about the answers.

1. Talk about the difference between static and macro definitions. When to use static and when to use macros. Make the constants you declare only work in the file you declare or the compiler will save them

Macro definition:

1). Generally speaking, we use macro definitions to define some simple “functions” (such as finding the maximum value of two numbers) such as: define the constant PI

# define PI (3.1415926)Copy the code

Define a function


#define MIN(A,B) ((A) < (B) ? (A):(B))
Copy the code

We do not modify the macro definition

  1. Using macro definitions can greatly simplify our code

For example, when we wrote the singleton, we wrote before

#import "ShareSingleton.h"

@implementation ShareSingleton

+(instancetype)shareSingleton {

    static ShareSingleton *leader = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        leader = [[ShareSingleton alloc]init];
    });
    return leader;
}
@end
Copy the code

// If we use macro definition we can write:

#define DISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
#import "ShareSingleton.h"
@implementation ShareSingleton

+(instancetype)shareSingleton {

    static ShareSingleton *leader = nil;
    DISPATCH_ONCE_BLOCK(^{
        leader = [[ShareSingleton alloc]init];
    })
    return leader;
}
@end
Copy the code

A macro definition is essentially a precompiled instruction that pays some instructions to the corresponding variable before the program runs.

To recap: Static variables are stored in the global variables area and have the same life cycle as the program. The life cycle defined by a macro definition is related to the life cycle of the carrier.

Static is only visible in the declared class. After ending in a declared class, the same value is used again.

2. What do you think of the proxy notice? What is the difference between them? First, let’s talk about proxy notifications together. The first response is passing values. Ok, below slowly say each usage and the difference.

Notification center

With NSNotification, you can send data and messages to multiple objects (multiple passes). The proxy can only send data and messages to one object (single pass) through protocol (proxy mode). Only one delegate can be set for an object for the same protocol. So singletons cannot be broached (multipoint callbacks can be used, insight below).

The agent is more concerned with the transmission of process information: for example, when making a network request, it may want to know whether the request has started, whether the data has been received, whether the data has been received, or whether the data has been received.

Distinction: The distinction between agency and notification should be primarily one to one and one to many. The delegate multi-point callback is more convenient than notification, which makes the project easier to maintain.

3. Tell me your understanding of memory management.

Memory Management Principles

The reference count increases and decreases equally, and after the reference count drops to zero, this space should not be used. Alloc retain or copy increases the memory reference count. You need to use release or autorelease to reduce the reference count in memory. In a piece of code. Increase and decrease the same number of times.

The use of autoreleasepool

Control the release of an AutoRelease object via AutoReleasepool. Send an AutoRelease message to an object. When this object is released depends on the Autoreleasepool

The copy method is different from retain. If an object wants to copy and make its own copy, it needs to implement the NSCopying protocol and define the details of the copy. OC uses the reference counting mechanism to manage memory. When alloc copy retain is used to increase the reference count, release and autorelease are used to reduce the reference count. When the reference count is 0, the memory occupied by the object is reclaimed by the system.

An autorelease is a reference minus one at some future time, not immediately.

Not any object can accept a copy message. Only objects that accept the NSCoping protocol accept copy messages.

4. Talk about your understanding of iOS performance optimization.

When we talk about iOS performance tuning, the first thing that comes to mind is the tableView optimization. Table view optimization can be viewed from the following aspects:

1). Tableviewcell should be rendered as far as possible to avoid allocating resources such as UIFont, NSDateFormatter or any object needed during drawing. It is recommended to use class-level initialization methods to perform allocation and store it as static variables.

2). The problem of layer rendering The transparent layer will affect the rendering performance. The system must mix the transparent layer with the view below to calculate the color and draw it. Reducing transparent layers and replacing them with opaque ones can greatly improve rendering speed.

We should try to avoid writing so much code in the cellForRowatIndexpath proxy method of TableView, which can not only simplify the code to facilitate maintenance and management, which is also helpful for the operation of the program.

4). Try to use pure code for complex views

When a UITableViewCell has multiple child views, the IOS rendering mechanism slows things down. Overwriting drawRect to draw content directly improves performance, rather than initializing some label or imageView at class initialization time.

(The following is from yykit author ibireme, this is the source link)

Here are some CPU resource consumption causes and solutions as well as GPU resource consumption causes and solutions

The creation of an object allocates memory, adjusts properties, and even reads files, consuming CPU resources. You can optimize performance by replacing heavy objects with lightweight objects. For example, CALayer is much lighter than UIView, so controls that do not need to respond to touch events are better displayed with CALayer. If the object does not involve UI operations, try to create it in the background thread, but unfortunately controls that contain CALayer can only be created and manipulated in the main thread. Creating view objects in Storyboard is much more expensive than creating them directly in code, and Storyboard is not a good technology choice for performance-sensitive interfaces.

1). Object creation should be delayed as much as possible and spread over multiple tasks. Although this is a bit of a hassle to implement and doesn’t offer many advantages, if you can do it, try it. If objects can be reused and the cost of reuse is less than releasing and creating new objects, then such objects should be reused in a cache pool whenever possible.

2). Object tuning Object tuning is also often a CPU drain. Here’s a special word for CALayer: CALayer has no properties inside it. When a property method is called, it temporarily adds a method to the object through the runtime resolveInstanceMethod and stores the corresponding property value in an internal Dictionary. It also notifies the delegate, creates animations, and so on, which is very resource-intensive. UIView’s display-related properties (frame/bounds/ Transform, for example) are actually mapped from the CALayer properties, so adjusting these UIView properties consumes far more resources than normal properties. You should minimize unnecessary property changes in your application. There are a lot of method calls and notifications between UIView and CALayer when view hierarchies are adjusted, so you should avoid adjusting view hierarchies, adding and removing views when optimizing performance. 3). Object destruction The destruction of objects consumes few resources, but it adds up to something that cannot be ignored. Usually when a container class holds a large number of objects, the resource cost of their destruction becomes apparent. Similarly, if an object can be released in a background thread, move it to the background thread. Here’s a little Tip: Capture an object in a block, throw it on a background queue, send a random message to avoid compiler warnings, and let the object be destroyed in the background thread. Such as:

NSArray *tmp = self.array;
self.array = nil;
dispatch_async(queue, ^{
    [tmp class];
});
Copy the code

4). Some calculations

View layout calculation is the most common CPU drain in an App. If the view layout is precomputed in the background thread and cached, there are few performance issues in this place. Regardless of the technology to the view layout through, it will eventually fall for UIView. The frame/bounds/center on the adjustment of the property. As mentioned above, adjusting these attributes is very expensive, so try to calculate the layout in advance and adjust the corresponding attributes at once if necessary, rather than multiple, frequent calculation and adjustment of these attributes. Autolayout is a technology advocated by Apple itself and can be a great way to improve development efficiency in most cases, but Autolayout can often cause serious performance problems for complex views. As the number of views grows, the CPU consumption from Autolayout increases exponentially. For more information, see pilky.me/36/. If you don’t want to manually adjust the frame and other attributes, you can use some tools to replace (such as common left/right/top/bottom/width/height and quick properties), or use ComponentKit, AsyncDisplayKit framework, etc.

If an interface contains a large amount of text (such as weibo and wechat moments, etc.), text width and height calculation will occupy a large portion of resources and is inevitable. If you have no special requirements for text display, you can refer to the internal implementation of UILabel: With [NSAttributedString boundingRectWithSize: options: context:] to calculate the text width is high, Use – [NSAttributedString drawWithRect: options: context:] to draw text. Although these two methods perform well, they still need to be put into background threads to avoid blocking the main thread.

5). Text drawing

If you draw text in CoreText, you can create a CoreText typeset object and do the calculation yourself, and the CoreText object can be saved for later drawing. All text content controls that can be seen on the screen, including UIWebView, are at the bottom of the page formatted and drawn as bitmaps through CoreText. Common text controls (UILabel, UITextView, etc.), its typesetting and drawing are carried out in the main thread, when the display of a large number of text, the CPU pressure will be very large. There is only one solution, and that is a custom text control that asynchronously draws text using TextKit or the low-level CoreText. Once the CoreText object is created, it can directly obtain the width and height of the text, avoiding multiple calculations (once when the UILabel size is adjusted, and again when the UILabel is drawn). CoreText objects take up less memory and can be cached for later multiple renders.

6). Picture decoding

When you create an image using UIImage or CGImageSource methods, the image data is not immediately decoded. The image is set to UIImageView or calayer.contents, and the data in the CGImage is decoded before the CALayer is submitted to the GPU. This step occurs on the main thread and is unavoidable. If you want to get around this mechanism, it is common to draw images into CGBitmapContext in the background line and then create images directly from the Bitmap. At present, the common network photo library has this function.

7). Image rendering

Drawing an image usually refers to the process of drawing an image onto a canvas using methods that begin with CG, and then creating and displaying the image from the canvas. The most common place to do this is inside [UIView drawRect:]. Since CoreGraphic methods are usually thread-safe, drawing images can easily be put into background threads. The process for a simple asynchronous drawing looks something like this (it’s much more complicated than this, but the principle is the same)

dispatch_async(backgroundQueue, ^{ CGContextRef ctx = CGBitmapContextCreate(...) ; // draw in context... CGImageRef img = CGBitmapContextCreateImage(ctx); CFRelease(ctx); dispatch_async(mainQueue, ^{ layer.contents = img; }); });Copy the code

Causes and solutions of GPU resource consumption

1. Texture rendering

All bitmaps, including images, text and rasterized content, are eventually committed from memory to video memory and bound to the GPU Texture. Both the process of submitting to video memory and the process of GPU adjusting and rendering Texture consume a lot of GPU resources. When a large number of images are displayed in a short period of time (such as when the TableView has a large number of images and slides quickly), the CPU usage is very low and the GPU usage is very high, and the interface will still drop frames. The only way to avoid this situation is to minimize the display of a large number of pictures in a short period of time, and to display as many pictures as possible. When the image is too large to exceed the maximum texture size of the GPU, the image needs to be preprocessed by the CPU, which will bring additional resource consumption to the CPU and GPU. Currently, iPhone 4S and above models, texture size upper limit is 4096×4096, more detailed information can be seen here: iosres.com. So try not to let images and views exceed this size.

When multiple views (or Calayers) are displayed on top of each other, the GPU blends them together first. If the view structure is too complex, the mixing process can also consume a lot of GPU resources. To reduce GPU consumption in this situation, applications should minimize the number and level of views and indicate opaque attributes in opaque views to avoid useless Alpha channel composition. Of course, this can also be done by pre-rendering multiple views as a single image

3. Image generation

CALayer’s border, rounded corners, shadows and masks, CASharpLayer’s vector graphics display, usually trigger offscreen rendering, which usually happens on the GPU. When a list view shows a large number of calayers with rounded corners and a quick swipe, you can observe that the GPU resource is full and the CPU resource consumption is low. The interface still slides normally, but the average number of frames drops to a very low level. ShouldRasterize to avoid this, try turning on the calayer.shouldrasterize property, but this will shift the off-screen rendering onto the CPU. For situations where only rounded corners are needed, you can also simulate the same visual effect by overlaying the original view with an already drawn rounded corner image. The most radical solution is to draw the graphics that need to be displayed as images in background threads, avoiding rounded corners, shadows, masks, and other attributes.

How do I detect app fluency?Copy the code

“Premature optimization is the root of all evil.” When requirements are uncertain and performance problems are not obvious, there is no need to try to optimize, but to implement functions as correctly as possible. When optimizing performance, it is also best to go through the process of modifying the code -> Profile -> modifying the code, focusing on the areas that deserve the most optimization. If you need a clear FPS indicator, try KMCGeigerCounter. CPU sluggage can be detected by the built-in CADisplayLink. It uses a 1×1 SKView to monitor the gPU-brought katton. This project has two minor problems: although SKView can monitor GPU lag, introducing SKView itself will bring a little extra resource consumption to CPU/GPU; This project has some compatibility issues with iOS 9 and needs to be tweaked slightly.

5. Have you ever used unit tests? How to do unit tests well?

What are unit tests?

Unit Tests: The following is from Wikipedia unit tests

In computer programming, Unit Testing (English: Unit Testing), also known as module Testing, is a test for the correctness of the program module (the smallest Unit of software design). A program unit is the smallest testable part of an application. In procedural programming, a unit is a single program, function, procedure, etc. For object-oriented programming, the smallest unit is a method, including methods in a base class (superclass), an abstract class, or a derived class (subclass).

Generally speaking, programmers will conduct at least one unit test for every modification of the program. It is likely that many unit tests will be conducted before and after the writing of the program to verify that the program meets the working objectives specified in the software specification and there are no program errors. While unit testing is not necessary, it is not bad, and it involves policy decisions for project management. Each ideal test case is independent of the others; To isolate modules while testing, dummy programs such as STUbs, Mock [1], or FAKE are often used. Unit tests are typically written by software developers to ensure that the code they write meets the software requirements and follows development goals. It can be implemented either very manually (by pen and paper) or as part of build automation.Copy the code

What are the benefits of unit testing?

One of the benefits of unit testing is that we can only test a single module, we can test a single module for problems. For example, we often write test demos during development. The test demo we wrote worked as well as we needed, so we could use the demo to debug our project.

  • To adapt to the change

Unit testing allows programmers to refactor the code in the future and ensure that the module still works correctly (composite testing). The process is to write unit tests for all functions and methods so that if a change causes an error to occur, it can be quickly located and fixed.

Readable unit tests make it easy for programmers to check that pieces of code are still working. Well-designed unit test cases cover all paths of program unit branches and loop conditions.

In a continuous unit test environment, unit tests can continue to be used to accurately reflect the performance of executable programs and code when any changes occur, through their inherent ongoing maintenance efforts. With the aforementioned development practices and coverage of unit tests, accuracy can be maintained minute-by-minute.

  • Simplify integration

Unit testing eliminates the unreliability of program units and takes a bottom-up test path. Integration testing is made easier by testing program components first and then component assembly.

The need for manual integration testing is controversial in the industry. Although a well-designed unit test architecture appears to implement integration testing, since integration testing requires human evaluation of aspects that can only be verified by human factors, unit testing is not a credible substitute for integration testing. Some people believe that with sufficient automated test systems, human integrated test teams are no longer necessary. In fact, the real requirements ultimately depend on the characteristics and usage goals of the product being developed. In addition, manual or manual testing depends heavily on the resources available to the organization. [Source request]

  • document

Unit tests provide a kind of documentation of the system. By looking at what unit tests provide and how they are used in unit tests, developers can intuitively understand the underlying API of a unit.

Unit tests embody the key characteristics of program unit success. These characteristics can indicate correct and incorrect use of program units, as well as negative aspects of program units that need to be captured. Although many software development environments rely on more than just code as product documentation, unit testing and unit testing itself do document the above key features of program units.

On the other hand, traditional documentation is susceptible to implementation and timeliness (design changes, feature extensions, etc., often fail to keep the documents up to date when they are not too strict).

  • Express design

    In the practice of test-driven development, unit testing can replace formal design. Each unit test case can be viewed as a design element such as a class, method, and behavior to be observed. The following Java example can help illustrate this.

Of course, unit tests lack the readability of diagrams, but UML diagrams can be generated for most modern programming languages in free tools (often available from IDE extensions), making it difficult to purchase expensive UML design suites. Free tools, similar to those based on the xUnit framework, output test results to some graphical tool system that can be generated for human reading.

  • Separate the interface from the implementation

Because many classes reference other classes, tests on this class often require tests on other classes. One of the most common examples is a database-dependent class: to test it, testers often write code to manipulate the database. This is not true because unit tests should not go beyond the boundaries of the class to be tested.

Instead, the software developer should create an abstract interface to the database connection and then implement a mock object for that interface. By abstracting the attachments required by the code (temporarily reducing the mesh coupling effect), these individual program units can be tested more fully than the former. Higher quality code units also provide better maintainability.Copy the code
  • limited

Testing can’t find all program errors, and unit testing is no exception. By definition, unit tests only test the functionality of the program unit itself. Therefore, it cannot find integration errors, performance problems, or other system-level problems. Unit testing is more effective in conjunction with other software testing activities. Like other forms of software testing, unit testing can only indicate detected problems, not the absence of untested errors.

Software testing is a combinatorial problem. For example, every Boolean decision statement requires at least two tests: one that returns true and one that returns false. As a result, programmers typically write three to five lines of test code for each line of code written. [3] This obviously takes time and may not be worth the investment. There are also problems that simply cannot be detected – such as those that are uncertain or involve multiple threads. In addition, the code written for unit tests can have bugs just like the code being tested. Fred Brooks, in his book The Myth of the Man-month, gives an example: “Never take two timekeepers to the beach. Always bring one or three “. Meaning, if two timers conflict, how do you know which one is right? To reap the benefits of unit testing, a sense of discipline should be developed during software development. It is necessary to keep careful records, not only of the tests performed, but also of the history of changes to the corresponding source code and other software units. That is, using a version control system is essential. If a subsequent release fails a unit test that passed a previous test, the version control system can provide a list of changes made to the source code over the corresponding time period.

It is essential to develop a daily habit of looking at unit test cases for failed tests and identifying the cause of errors in time. Without such a process, embodied in the team workflow, the unit test series will move out of sync, resulting in more and more errors and less and less efficient unit test case series.Copy the code

Unit testing in iOS

In development, unit testing is often used to test the function of a module, that is, to test the module independently. The most used should be the test module function and interface debugging function. There are also advanced uses for unit testing, automated testing and automated distribution.

OCUnit (testing with XCTest) is essentially Apple’s own testing framework, and that’s what we’ll focus on. GHUnit is a visual testing framework. (With it, you can click on the APP to decide which method to test, and you can click to see test results, etc.) OCMock is to simulate the return value of a method or property. Why do you do this, you might wonder? Don’t you just use the model object generated by the model and pass it in? The answer is yes, but there are special circumstances. For example, if you are testing method A, method B is called from method A, and method B has parameters that are not provided by method A. At this point, you can use OCMock to simulate the value returned by method B. (This can be done without affecting the test.) In addition to this, OCMock can also be used to simulate the returned data without a network. UITests are ests that implement automatic interface clicking, text input and other functions through coding. By manual operation to cover all the test cases is very difficult, especially after adding new function, the function of the old to retest again, this led to the tests need to spend very much time for regression testing, here have a lot of repetitive work, and some of these repetitive work can be done automatically, This is where UITests help solve the problem.

6. What do you know about local data persistence? Which ones do you prefer to use? Why?

The data storage methods are as follows:

1, FMDB (common) 2, Sqlite(second) 3, Coredata(second) 4, NSUserdefaults(most) 5, Serialization deserialization (archive and file) 6, MongoDB(minority)

The most discussed one is FMDB, for the simple reason that it is a relational database and easy to use (as opposed to Sqlite, which has not been packaged and processed). Sqlite and CoreData, of course, are used mainly for caching. Because in order to give users a better experience in development, we use the form of caching. The usual thing to do is set up a database locally (local backend).

7. Talk about the pros and cons of the MVC design pattern

Programming has been instilled with the MVC design pattern, and the specific advantages and disadvantages of using MVC can be understood through the following introduction.

First, MVC principle

MVC is a program development and design pattern, which realizes the separation of display module and function module. It improves the maintainability, portability, extensibility and reusability of the program, and reduces the difficulty of developing the program. It is mainly divided into model, view, controller three layers.

  1. It is the main part of the application program, including business logic module (Action, DAO class in the Web project) and data module (POJO class). The model is independent of the data format, so that a single model can provide data for multiple views. Because code applied to a model can be written once and reused by multiple views, code duplication is reduced

  2. View Is the interface with which users interact. A view on the Web generally consists of JSP and HTML

  3. The controller receives the request from the interface and gives it to the model for processing. In this process, the controller does nothing but performs a connection.

Second, advantages of MVC

  1. Multiple views can be created and used simultaneously at run time for a model. The change-propagation mechanism ensures that all related views get model data changes in a timely manner, thereby synchronizing the behavior of all associated views and controllers.

  2. The pluggability of views and controllers allows view and controller objects to be changed, dynamically turned on and off as needed, and even replaced at run time.

  3. Portability of the model. Because models are view-independent, a model can be ported independently to work on a new platform. All you need to do is make new changes to the view and controller on the new platform.

  4. The underlying framework structure. Application frameworks can be built based on this model, not just in the design of design interfaces.

Three, MVC shortcomings

  1. The complexity of system structure and implementation is increased. For a simple interface, strictly following MVC to separate model, view and controller will increase the complexity of the structure, and may cause excessive update operations, reducing operation efficiency.

  2. Too tight a connection between view and controller. Views and controllers are separate, but truly interconnected parts. Views without controllers have limited applications, and vice versa, which impedes their independent reuse.

  3. Inefficient access by views to model data. Depending on the model’s operation interface, the view may require multiple calls to get enough display data. Needlessly frequent access to unchanged data can also hurt operational performance.

  4. Currently, schemas are not supported by advanced interface tools or constructors. Adapting these tools to fit MVC needs and building separate parts is costly, which makes MVC difficult to use.

8. Talk about your understanding of multithreading, what are the implementations of multithreading that you often use, and their strengths and weaknesses.

NSOperationQueue is used to manage subclassed NSOperation objects and control the number of concurrent threads. Both GCD and NSOperation can manage threads. The difference is that NSOperation and NSOperationQueue are multi-threaded object-oriented abstractions. The advantage of using NSOperation in the project is that NSOperation is highly abstract to threads. Using NSOperation in the project will make the program structure of the project better. The design idea of subclassing NSOperation has the advantages of object-oriented (reuse and encapsulation), making the implementation supported by multi-threading and the interface simple. Recommended for complex projects.

The advantage of using GCD in a project is that GCD itself is very simple and easy to use. For uncomplicated multi-threaded operations, it will save the amount of code, while the use of Block parameter will make the code more readable, so it is recommended to use it in simple projects.

When to use multithreading?

In most cases, multi-threading is mainly needed to deal with a large number of IO operations or processing situations need to spend a lot of time and so on, such as: reading and writing documents, video image collection, processing, display, save, etc..

What does multithreading do?

It can solve the load balancing problem and make full use of CPU resources. In order to increase CPU utilization, multithreading is used to accomplish several things simultaneously without interfering with each other.

What are the ways iOS can implement multithreading?

There are three main approaches.

1, the NSThread.

2, NSOperation.

3, the GCD.

Several solutions to multi-thread security problems?

Use the lock. Locks are the foundation of threaded programming synchronization tools. Locking allows you to easily protect a large area of your code so that you can ensure code integrity. Use POSIX mutex; Use the NSLock class; Use the @synchronized directive, etc.

What is the thread – split callback main thread method? What does it do?

To return to the main thread:

(1). performSelectorOnMainThrea

[self performSelectorOnMainThread:<#(SEL)#>withObject:<#(id)#>waitUntilDone:<#(BOOL)#>];
Copy the code

(2). GCD

dispatch_async(dispatch_get_main_queue(), ^{ 
});
Copy the code

(3). NSOperationQueue

[[NSOperationQueue mainQueue]addOperationWithBlock:^{
}]
Copy the code

Function: the main thread is to display THE UI interface, most of the sub-threads are for data processing.

PS: the highest state is asynchronous single thread, known as coroutine. See the ASIO user-level task scheduling in Boost

9. Talk about your understanding of object orientation and process orientation.

Simple comparison

Process orientation is like a careful housekeeper, taking everything into account. Object orientation is like a home appliance. You only need to know what it does, not how it works. “Process oriented” is an event – centered programming philosophy. It is to analyze the steps needed to solve the problem, and then use functions to write the steps, and call in order. Object oriented is the programming idea centered on object.

A simple example: a car starts, a bus arrives at a station

This is two events for process-oriented, the car starts one event, the car arrives at the station another event, and in process-oriented programming we care about the event, not the car itself. Two functions are formed for the above two events and then called in sequence. Whereas for object orientation, we care about objects like cars, and these two events are just the behavior of those objects. And there is no compulsion on the order of the two actions.

A contrast of two ideas

Process-oriented is actually the most practical way to think about it, because we always solve problems step by step. (for one simple thing, when we first learned object-oriented languages like c++, we were always inadvertently procedural oriented!) . In fact, even object oriented thought also includes process oriented thought. Process oriented thought needs to form events, that is, functions. Object oriented thought needs to abstract out classes, and will define the “behavior” and methods of this kind of object. However, both process-oriented functions and object-oriented methods accomplish the same purpose. It can be said that process oriented approach is a basic approach, it considers the actual implementation, in general, process oriented approach is gradually refined from the top down, its most important is modular thinking. The object – oriented approach is to objectify things, including their properties and behavior. There is an advantage to being procedural oriented when the program is small, and the flow of the program is very clear. Just like the process of starting and arriving at the station, the orientation process can clearly reflect the process. However, the object orientation only abstracts a Bus class, including two behaviors of launching and arriving, and the specific execution order cannot be reflected.

Understanding the nature of process orientation and object orientation

Process orientation is to analyze the steps needed to solve the problem, while object orientation is to decompose the things that constitute the problem into objects. The purpose of abstracting the object is not to complete a certain step, but to describe its behavior in the whole step of solving the problem. Process – oriented thinking mode is analysis and synthesis, object – oriented thinking mode is construction. For example, when c language solves problems, it usually defines data structures first and then constructs algorithms. Object-oriented solution abstracts the object and constructs a “closed” environment with defined data and algorithms to solve the problem. Process oriented design is more challenging, more technical, object oriented is mainly about the technology of object abstraction, once the abstraction is done, anyone can do the rest of the work. At the code level, the main difference between object-oriented and procedural is whether data is stored separately or together with operations. By providing data encapsulation, object orientation makes access to data reliable for an operation.

Process-oriented means that coding is treated as a thing and done step by step. Object-oriented means that coding is treated as a thing and done by the behavior of the thing (object).

In summary:

  • Object orientation is highly abstract.
  • Procedural orientation is top-down programming.
  • Object orientation must first build an abstract model, and then use the model directly.

Process-oriented means telling us exactly what we need to do step by step. That means we know exactly how it’s done.

Object orientation basically means we just need to know what the object we’re using does, and then we let the object do it. What we care about is not the process of implementation, but whether it can be achieved and the result of implementation. It is a manifestation of the abstraction of things.

The attached:

  1. Part of the answer is from YYKit author Ibireme: iOS tips for keeping the interface smooth

  2. Unit Testing Reference article: iOS Unit Testing (What it does and how to get started)

  3. Multithreading can be found in the article :iOS Development for a comprehensive analysis of multithreading

  4. Object – oriented process – oriented essence reference article: Process – oriented and object – oriented essential difference thinking

(To be continued)