Interview in 2021: Sort out an advanced iOS interview question!

1. What is the difference between NSArray and NSSet?

  • The storage addresses in NSArray memory are continuous, but NSSet is not continuous
  • NSSet is efficient and uses hash search internally; NSArray search needs to be traversed
  • NSSet accesses elements through anyObject, and NSArray accesses through subscripts

2 、 NSHashTable 与 NSMapTable

  • NSHashTable is a general version of NSSet, weak reference to elements, variable type; you can copy when accessing members
  • NSMapTable is a general version of NSDictionary, weak reference to elements, variable type; you can copy when accessing members

(Note: The difference between NSHashTable and NSSet: NSHashTable can set element weak reference/copyin through options, only variable types. But when adding objects, NSHashTable takes twice as long as NSSet.
The difference between NSMapTable and NSDictionary: Same as above)

3. Attribute keywords assign, retain, weak, copy

  • assign: Used for basic data types and structures. If the object is modified, the attribute value will not be automatically set to nil when it is destroyed, which may cause wild pointers.
  • weak: When the object reference count is 0, the attribute value will also be automatically set to nil
  • retain: strong reference type, equivalent to strong under ARC, but block cannot be modified with retain, because it is equivalent to assign is not safe.
  • strong: Strong reference type, equivalent to copy when modifying block.

4. How to automatically set the weak attribute to nil?

  • Runtime will make memory layout for weak attributes and construct a hash table: take the memory address of the weak attribute object as the key, and the weak attribute value (weak address itself) as the value. When the object reference count is 0 dealloc, the weak attribute value is automatically set to nil.

5. Block circular reference, internal modification of external variables, three types of blocks

  • block strongly refers to self, self strongly refers to block
  • Internal modification of external variables: Blocks are not allowed to modify the value of external variables. The external variables here refer to the memory address of the pointer in the stack. The function of __block is to put the memory address of the external variable in the stack into the heap as long as the variable is observed to be used by the block.
  • Three kinds of blocks: NSGlobalBlack (global), NSStackBlock (stack block), NSMallocBlock (heap block)

6. The underlying implementation principle of KVO? Trigger KVO manually? How does swift implement KVO?

  • KVO principle: When observing an object, the runtime dynamically creates a class inherited from the object and overwrites the setter method of the observed object. The overridden setter method will be responsible for notifying all observed objects that it is worth changing before and after calling the original setter method. Finally, the isa pointer of the object will point to the created subclass, and the object will become an instance of the subclass.
  • How to manually trigger KVO: In the setter method, manually implement two NSObject methods: willChangeValueForKey and didChangeValueForKey
  • Swift's kvo: a class inherited from NSObject, or directly implemented by willset/didset.

7. Why can't categroy add attributes? How to realize the addition? What is the difference with Extension? Category overrides the original class method? Multiple category call sequence

  • The memory layout of categroy has been determined when Runtime is initialized. There is no ivar, so attributes cannot be added by default.
  • Use runtime associated objects, and override the setter and getter methods.
  • Extenstion is created during compile time, and the member variable ivar can be added, which is generally used to hide the information of the class. You must have the source code of the class before you can add it. For example, NSString cannot create an Extension.
  • The category method will be copied to the front of the original when the runtime is initialized, and return directly when the category method is called, without calling the original class. How to keep the original class also called
  • The calling order of multiple categories is in accordance with the compilation order in Build Phases ->Complie Source.

8. The similarities and differences between the load method and the initialize method. ——Mainly talk about the execution time, their respective purposes, and will the method that does not implement the subclass call the parent class?
load initialize When the app is started, when the runtime is initialized, the calling sequence is called before the first method is called. Parent class -> this class -> classification parent class -> this class (if there is a classification directly calling classification, this class will not be called) Does a method that does not implement a subclass call the parent class? Whether to use the parent class to implement it?

6f701422a2ba6f7543e3b84932745bc6.webp

9. Understanding of runtime. ——Mainly how to find the cache when the method is called, how to find the method, how to forward when the method is not found, the memory layout of the object

When sending a message to an object in OC, the runtime will find the class to which the object belongs according to the isa pointer of the object, and then look for method execution in the method list of the class and the method list of the parent class. If the method execution is not found in the top-level parent class, the message will be forwarded: Method resoution (implementation method), fast forwarding (forwarded to other objects), normal forwarding (complete message forwarding. Can be forwarded to multiple objects)

10. What is the difference between SEL and IMP in runtime?

Each class object has a method list. The method list stores the method name, method implementation, and parameter type. SEL is the method name (number), and IMP points to the first address of the method implementation.

11. The principle and usage scenario of autoreleasepool?

  • The stack structure of a doubly linked list composed of several autoreleasepoolpages, objc_autoreleasepoolpush, objc_autoreleasepoolpop, objc_autorelease
  • Usage scenario: When the temporary variable is created multiple times and the memory rises, the release needs to be delayed
  • Memory structure of autoreleasepoolpage: 4k storage size


    ad4ebf22db8f844564a67187b0127f82.webp

12. When will the Autorelase object be released ?

Without adding the Autorelease Pool by hand, the Autorelease object is released at the end of the current runloop iteration, and the reason it can be released is that the system adds the automatic release pool Push and Pop to each runloop iteration.

13. The relationship between Runloop and thread? The mode of Runloop? What is the function of Runloop? Internal mechanism?

  • Each thread has a runloop, and the runloop of the main thread is started by default.
  • mode: Mainly used to specify the priority of the event loop at runtime
  • Function: Keep the program running continuously, handle various events at any time, save cpu resources (release resources without event rest), and render screen UI

14. The occurrence and avoidance of locks and deadlocks used in iOS

  • @synchronized, semaphore, NSLock, etc.
  • Deadlock: Multiple threads access the same resource at the same time, causing circular waiting. GCD uses asynchronous threads and parallel queues

15. The difference between NSOperation and GCD

  • The bottom layer of GCD is written efficiently in C language, and NSOperation is an object-oriented package of GCD. For special needs, such as canceling tasks, setting task priorities, and monitoring task status, NSOperation is more convenient to use.
  • NSOperation can set dependencies, while GCD can only be achieved through dispatch_barrier_async
  • NSOperation can observe the current operation execution status (execute/cancel) through KVO
  • NSOperation can set its own priority (queuePriority). GCD can only set the queue priority (DISPATCH_QUEUE_PRIORITY_DEFAULT), and cannot set the priority in the executed block
  • NSOperation can customize operations such as NSInvationOperation/NSBlockOperation, and GCD execution tasks can be customized encapsulated but not so high code reuse
  • GCD is efficient, NSOperation overhead is relatively high

16, oc and js interaction

  • Intercept url
  • JavaScriptCore (only for UIWebView)
  • WKScriptMessageHandler (only for WKWebView)
  • WebViewJavaScriptBridge (third-party framework)

17. What are the advantages of swift over OC?

18. The difference between struct and Class

  • Class can be inherited, struct cannot
  • class is a reference type, struct is a value type
  • struct requires mutating keyword modification when modifying property in function

19. Access control keywords (public, open, private, filePrivate, internal)

  • Public and open: public in the module, class and func can be accessed/overloaded/inherited, and can only be accessed from the outside; and open can both
  • private and filePrivate: private modifies class/func, which means that it can only be used inside the current class source file/func, and cannot be inherited or accessed externally; while filePrivate means that it can only be accessed within the current swift source file
  • internal: can be accessed in the entire module or app, the default access level, can be written or not

20, OC and Swift mixed editing

  • OC calls swift: import "project name-swift.h" @objc
  • swift calls oc: bridge file

21. Map, filter, reduce? What is the difference between map and flapmap?

  • map: Each element in the array is transformed by a certain method, and finally returns a new array (xx.map({ 0 *0}))
  • flatmap: map with similar, the difference does not exist in the array flatMap nil return, and will unpack optional; but also can be nested arrays opens into a th ([[1,2], [2,3,4 ],[5,6]] ->[1,2,2,3,4,5,6])
  • filter: User filters elements (xxx.filter({$0> 25}), filters out elements greater than 25 to form a new array)
  • reduce: Calculate the combination of array elements as a value and receive the initial value ()

bef4400cbc05de35bf684369d9db10ed.gif

22、guard与defer

  • Guard is used to process error data in advance, else exit the program, improve code readability
  • defer延迟执行,回收资源。多个defer反序执行,嵌套defer先执行外层,后执行内层

23、try、try?与try!

  • try:手动捕捉异常
  • try?:系统帮我们处理,出现异常返回nil;没有异常返回对应的对象
  • try!:直接告诉系统,该方法没有异常。如果出现异常程序会crash

24、@autoclosure:把一个表达式自动封装成闭包

25、throws与rethrows:throws另一个throws时,将前者改为rethrows

26、App启动优化策略?main函数执行前后怎么优化

  • 启动时间 = pre-main耗时+main耗时
  • pre-main阶段优化:
  • 删除无用代码
  • 抽象重复代码
  • +load方法做的事情延迟到initialize中,或者+load的事情不宜花费太多时间
  • 减少不必要的framework,或者优化已有framework
  • Main阶段优化
  • didFinishLauchingwithOptions里代码延后执行
  • 首次启动渲染的页面优化

27、crash防护?

  • unrecognized selector crash
  • KVO crash
  • NSNotification crash
  • NSTimer crash
  • Container crash(数组越界,插nil等)
  • NSString crash (字符串操作的crash)
  • Bad Access crash (野指针)
  • UI not on Main Thread Crash (非主线程刷UI (机制待改善))

28、内存泄露问题?

主要集中在循环引用问题中,如block、NSTime、perform selector引用计数问题。

29、UI卡顿优化?

30、架构&设计模式

  • MVC设计模式介绍
  • MVVM介绍、MVC与MVVM的区别?
  • ReactiveCocoa的热信号与冷信号
  • 缓存架构设计LRU方案
  • SDWebImage源码,如何实现解码
  • AFNetWorking源码分析
  • 组件化的实施,中间件的设计
  • 哈希表的实现原理?如何解决冲突

31、数据结构&算法

  • 快速排序、归并排序
  • Two-dimensional array search (each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, enter such a two-dimensional array and an integer, and judge the array Does it contain the integer?)
  • The traversal of the binary tree: determine the number of levels of the binary tree
  • Singly linked list judgment ring

32. Computer Basics

  1. http and https? socket programming? tcp, udp? get and post?
  2. tcp three-way handshake and four-way handshake
  3. The difference between process and thread

recommend

Guess you like

Origin blog.51cto.com/15146321/2674482