Answers to the latest iOS interview (underlying foundation) questions in 2022

Article directory

Runloop

1. What is the essence of RunLoop?

Answer: It is essentially an OC object, and there is also an isa pointer inside.

2. What is the relationship between Runloop and thread?

Answer: There is a key-value correspondence between threads and RunLoop, which is stored in a global Dictionary. Threads are keys, and RunLoops are values, which are lazy loaded.

3. What is the underlying data structure of Runloop? How many modes of operation are there? What are the CFRunloopMode under each run mode? What are their responsibilities?

Answer: The underlying data structure of Runloop (NSRunLoop is the encapsulation of CFRunLoop):
CFRunLoop, RunLoop object
Mode, operating mode
Source, input source/event source
Timer, timing source
Observer, the observer
system has registered 5 modes by default, and 3 are commonly used Several common Modes:
Default: App's default Mode, usually the main thread runs
UITracking in this Mode: Interface Tracking Mode, used for ScrollView` to track touch sliding, to ensure that the interface is not affected by other Modes when sliding.
Common: It is not a real mode, it is just a mark, such as: the marked Timer can run in Default mode and UITracking.

Modes that are basically not used:

UIInitialization : private mode, the state when the app starts, after loading the first page, it will be converted to the
internal mode of the Default GSEventReceive system, which is usually not used

4. What are the monitoring states of Runloop?

Answer: Entry->BeforeTimers->BeforeSources->BeforeWaiting (sleep)->AfterWaiting (wake up)->Exit->AllActivities

/* Run Loop Observer Activities */
typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) {
    kCFRunLoopEntry = (1UL << 0),                 // 即将进入Loop
    kCFRunLoopBeforeTimers = (1UL << 1),          // 即将处理Timer
    kCFRunLoopBeforeSources = (1UL << 2),         // 即将处理Source
    kCFRunLoopBeforeWaiting = (1UL << 5),         // 即将进入休眠
    kCFRunLoopAfterWaiting = (1UL << 6),          // 刚从休眠中唤醒
    kCFRunLoopExit = (1UL << 7),                  // 即将退出Loop
    kCFRunLoopAllActivities = 0x0FFFFFFFU         // 所有状态
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5. What is the workflow of Runloop?

insert image description here

6. What are the applications of Runloop?

Answer: The mode switching when scrolling the scrollview, the image download of the cell will execute multiple time-consuming operations separately, and
do a time-consuming task every time the RunLoop wakes up.

7. What is the kernel mode and user mode of Runloop?

Answer: There are two working states of the CPU: kernel state and user state (or management state and target state).
Kernel state: There are both operating system programs and ordinary user programs in the system. For safety and stability, the programs of the operating system cannot be accessed casually. This is the kernel state, which can use all hardware resources.
User mode: It cannot directly use system resources, nor can it change the working state of the CPU, and can only access the storage space of the user program itself.

threads, queues , locks

1. The relationship between threads and queues? Is it possible for a thread to exist in two queues?

Answer: A thread is the smallest task unit for system scheduling, and a queue is a data structure that stores and manages task units.

2. Will the queue necessarily create threads?

Answer: No, the synchronous execution method does not create a new thread, but only in the current thread.

Threads are divided into synchronous and asynchronous according to their execution methods, and they are divided into serial and parallel according to their queue management. There are four combinations in this way. In addition to the often-called main thread and main queue, there are six combinations combined with execution methods.

Synchronous serial, does not create threads, so it is still done one by one in the current thread

Synchronous parallelism does not create threads, so even if it is parallel, it is still done one by one in the current thread

Asynchronous serial, open up one more thread, and do tasks one by one in the newly opened thread

Asynchronous and parallel, open up multiple threads, and tasks are done together in the newly opened threads

Synchronize the home team, blocking

The asynchronous main team is the same as the asynchronous serial, because the main team is serial, but does not open a new thread, because the main thread is a global singleton

3. Can queues be created without limit?

Summary of 12 iOS technical interview questions and answers

The pdf is uploading... re-upload cancel 0 stars more than 10% resource 94KB

Uploading... Reupload Cancel

download

Answer: No, the queue is also an object, which takes up memory and is limited by hardware resources, so it cannot be created without limit.

4. Comparison of the advantages and disadvantages of PerformSelector & NSInvocation

Answer: The same point: have the same parent class NSObject Difference: When the number of parameters is <= 2, the use of performSelector: is simpler, but when the number of parameters is > 2, NSInvocation is simpler.

5. Can the use of gcd be cancelled?

Answer: dispatch_block_cancel can cancel tasks that have not yet been executed. Already running, interrupt with code

6. How to keep threads alive

Answer: If you want the thread not to die, you need to add a RunLoop to the thread

NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
// 往RunLoop里面添加Source\Timer\Observer,Port相关的是Source1事件
// 添加了一个Source1,但是这个Source1也没啥事,所以线程在这里就休眠了,不会往下走,----end----一直不会打印
[runLoop addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];
[runLoop run];
  • 1
  • 2
  • 3
  • 4
  • 5

GCD

The difference between GCD and NSOperation, and the difference between functional methods.

Answer:
NSThread is an early multi-threading solution. In fact, it encapsulates the PThread thread management code in C language into OC code.
GCD is a multi-threading technology that replaces NSThread, C syntax + block. Powerful. Make full use of multi-core, the most efficient
NSOperationQueue encapsulates GCD as OC syntax, and adds several new functions compared to GCD. The maximum number of concurrent threads cancels tasks in the queue and suspends tasks in the queue. You
can adjust the execution order of tasks in the queue, and support KVO through priority threads relying on NSOperationQueue. This means you can observe the state properties of tasks.
But the execution efficiency of NSOperationQueue is not as high as that of GCD, so in half of the cases, we use GCD to complete multi-threaded operations.

The difference between gcd queue

Answer:
GCD is a multi-threading technology that replaces NSThread, C syntax + block. Powerful.
Make full use of multi-core, the most efficient NSOperationQueue encapsulates GCD as OC syntax, and adds several new functions compared to GCD.
The maximum number of concurrent threads.
Cancel the tasks in the queue.
Pause the tasks in the queue
. You can adjust the execution order of the tasks in the queue. Through the priority
thread, it depends on
NSOperationQueue to support KVO. This means you can observe the state properties of tasks.
But the execution efficiency of NSOperationQueue is not as high as that of GCD, so in half of the cases, we use GCD to complete multi-threaded operations.

How does group implement barrier-like functions?

NetEase iOS Job Interview Questions

docx is uploading... reupload cancel 0 stars more than 10% resource 107KB

Uploading... Reupload Cancel

download

Answer: The barrier function, no matter how many asynchronous operations before the barrier have to be executed, the operations behind the barrier will be executed.
You can try to implement it with semaphores, such as A, B, C, barrier, and D concurrently, but it is hoped that D will not start until ABC is completed.
Set the maximum value of the thread semaphore to 3, ABC is executed first, and D starts after ABC is executed

How does the GCD group achieve synchronization? (What else can be used to achieve it?)

Answer: The first serial queue, the second parallel queue, the third packet, and the fourth semaphore.
Serial, execute one by one, has the effect of synchronous operation
Parallel, first open an asynchronous thread, put multiple synchronous threads in the asynchronous to perform parallel grouping, dispatch_group_notify() provides a semaphore
to know when the group ends ,
The role of semaphore and lock is similar, it can be used to achieve synchronization

Execute an NSThread task, how to terminate it during execution?

Answer: //Monitor whether the current thread has been canceled, and if it is canceled, the thread will exit. Detect the canceled mark in the thread, and then execute the exit if ([[NSThread
currentThread] isCancelled]) { [NSThread exit]; }

How does iOS NSOperation terminate/cancel tasks?

Answer: NSOperation cannot cancel the task that is being executed. You can consider using a condition to do it. If the condition is met, the task will be executed. If the condition is not met, the task will not be executed.

Multi-threaded, asynchronous execution (async) will a performSelector be executed? What if afterDelay is added?

Answer: performSelector will be executed, but afterDelay will not be executed; the reason is that performSelector simply calls a certain function directly, and afterDelay executes an NSTimer in the sub-thread. Note: the runloop in the sub-thread is not started by default. If you want afterDelay to take effect , to run the runloop when the thread has a transaction, it needs to execute [[NSRunLoop
currentRunLoop] run].

GCD implements NSOperationQueue

Answer: Inexplicable question, do you want to explain how to use GCD to create NSOperationQueue?

The role of DispatchQoS

Answer: Thread optimization tells the system what type of task it is.
user_interactive: user interaction (hope to complete as soon as possible, the user expects the result very much, don't put too much time-consuming operation)
user_initiated: user expectation (don't put too much time-consuming operation)
default: default (not for programmers, used to reset the pair column used)
utility: utility (time-consuming operation, you can use this option)
background: background
unspecified:
Priority prior to iOS 7.0 is not specified
priority_high: high priority
priority_default: default priority priority_low
: low priority
priority_backgroud: background priority

 

Guess you like

Origin blog.csdn.net/super_man_ww/article/details/126662274