After the naked resignation at the end of last year, I participated in the interview preparation this year. Tidy it up and save it for someone who needs it. PS: Nothing don’t resign naked, really affect the mentality.
1. How much memory an instance object occupies
Using 16 bytes, the object's member variable has only one ISA pointer, 8 bytes in size on 64-bit systems, and only 8 bytes used. But the underlying implementation of alloc does this, assigning 16 bytes if it's less than 16. Class_getInstanceSize gets instance sizes that are memory-aligned. Is the total amount of memory taken up by instance variables. Malloc_size Gets the size of memory allocated to the instance object. OC allocates space to instance objects according to 16, 32, 48, 64, 80, 96... Increasing by multiples of 16.Copy the code
2. Classification of OC objects
Instance objects store the following information in memory: isa pointer Other member variables Class objects store the following information: Isa pointer Superclass pointer class attribute information (@property) Class object method information (instance method) class protocol information (ivAR) class member variable information (ivar, describes the type and name of the member variable, Rather than an instance specific value)... The structure of a class object is the same as that of a metaclass object. In a class object, the class method information is empty, while in a meta-class method, the attribute information, object method information, protocol information, and member variable information are empty.Copy the code
3. Verify that the superclass in NSObject’s meta-class object points to its own class object.
You can create a class Person that doesn't implement the class method +test, define a +test in the NSObject class, implement a -test method, and find that [Person test] works fine. And that just proves the question. Person finds the metaclass through ISA, finds no method, finds the metaclass on NSObject through superClass, finds no method, finds the class object through superClass, finds the method.Copy the code
4, KVO (Person, int age)
After adding an observer to the object, the Runtime generates a new class, NSKVONotifying_Person, and the ISA pointer points to the newly generated NSKVONotifying_Person class, which overwrites the property method. This class has setAge, class, _isKVOA, dealloc methods, In setAge, we call foundation NSSetIntValueAndNotify and we do willChangeValueforkey in there and we call setAge didchangeValueForkey. Manually trigger KVO with calls to willChangeValueforkey and didChagneValueforkeyCopy the code
5, KVC
When assigning a value to an object using KVC, the following order of methods and attributes will be called to check setKey: Method exists, if there is a direct call, if not enter the next step for + (BOOL) accessInstanceVariablesDirectly method return value, the default return YES YES: can access member variables, to enter the next step NO: -(void)setValue:(id)value forUndefinedKey:(NSString *)key If there is no member variable, then -(void)setValue:(id)value forUndefinedKey:(NSString *)key is called, If a method does not exist, an exception will be thrown. If a method does not exist, an exception will be thrown. GetKey, key, isKey _key from left to right, if there is a way, direct call, end value, if not into the next call + (BOOL) accessInstanceVariablesDirectly see whether can access member variables. Default YES YES: access member variables, go to the next step NO: -(id)valueForUndefinedKey:(NSString *)key; _key, _isKey, key, isKey from left to right, if there's a member variable, just call it, end of value if there's no member variable, -(id)valueForUndefinedKey:(NSString *)key method, which is called when implementedCopy the code
6, the category
The underlying structure of a Category after compilation is struct category_t, which stores classified object methods, class methods, attributes, and protocol information. When the program is running, the Runtime will classify the Category data, What is the difference between a Category and a Class Extension when merged into Class information (Class object, metaclass object)? When Class Extension is compiled, its data is already contained in the Class information and Category data is merged into the Class information at runtimeCopy the code
Load and Initialize
So load, when you start up your program it's going to load all the classes and then the category load method, depending on the order in which you compile it. The parent class calls load before the child class calls load-> because the logic in the underlying source code is to pass the parent class recursively into a function. It doesn't matter that load is called in compile order, load is only called once. Can the load method be inherited by subclasses? Initialize calls initialize of the parent class first and then the subclass class. Initialize calls initialize of the parent class first and then the subclass class. Initialize calls initialize of the parent class. The invocation is message sending. If a subclass (Student) does not implement the initialize method, but prints the parent class (Person) initialize twice when the subclass sends its first message. The first Person (Test1) -initialize print is actually called when the Person class is initialized. In OC, the class methods are called in the following order using the message mechanism: The class object finds the metaclass object through ISA, looks for a method in the list of methods on the metaclass object, calls it if it has one, finds the parent metaclass object through the superclass of the metaclass object, looks for the method in the list of methods on the parent metaclass object, So, Student actually calls objc_msgSend([Student class], @selector(initialize)), But because Student does not implement the initialize method, Student calls the initialize method of its parent class PersonCopy the code
8. Associated objects
You can add attributes, protocols, and methods to a category, but you can't add member variables. As you can see from the underlying structure, there is no place to store member variables. You can add member variables to a category via the Runtime. Member variables associated with an object are managed at the bottom level and are not merged into the member list of the class object. What is the underlying implementation of associative objects? The core has four objects: AssociationsManager AssociationsHashMap, ObjectAssociationsMap, and OjbectAssociationCopy the code
9, block,
The underlying structure of a block is a structure, and the code block of a block is also encapsulated as a function. The difference between block capturing variables is that the auto variable (value capturing) (destroyed when out of scope) is used, which actually generates one more captured member variable in the structure weight. Static variables capture the address of a variable. A pointer variable is added to the block structure. If the value of the variable is changed after the block is defined, the value of the block is changed. Global variables (not captured) are not captured in a block and are used directly, and if the value changes, so does the use in the block. Local variables (auto, static) are captured; auto is a value reference; static is a pointer reference. There are three types of blocks: global, stack, and heap. Blocks are located in different memory areas, data areas, stack areas, and heap areas. MRC block types: those that do not use auto are __NSGlobalBlock__ types, including block arguments, static variables, and global variables. A block that uses an auto variable internally is of type __NSStackBlock__. A block of type __NSStackBlock__ calls copy and then __NSMallocBlock__ copies the block from the stack to the heap (which is why the logic used to copy the block in the method arguments first). A block of type __NSGlobalBlock__ calls copy and remains of type __NSGlobalBlock__ (still in the data area). __NSMallocBlock__ blocks are of type __NSMallocBlock__ (no new blocks are generated, the reference count is +1). Blocks in the stack do not retain the auto variable of the object type, only when the block is copied to the heap (reference count +1) when the block in the heap is released, The auto variable of the object type is released (reference count -1). If the auto variable of the object type is zero, the block under ARC will be released: In ARC mode, the compiler automatically copies blocks from the stack area to the heap area as appropriate. 1. When a block of type __NSStackBlock__ is returned as a function value, the returned block is copied to the heap. 2. Assigning a block of type __NSStackBlock__ to the __strong pointer copies the block to the heap. If there is no stackblock referenced by the __strong pointer, it is still a Stackblock. 3. Block is in the heap when it is used as a method parameter in Cocoa API. 4. When a block is a method parameter of the GCD API, the block is in the heap. In both ARC and MRC, the block in the stack does not strongly reference the captured object type auto variable (reference count +1). It only references the object type Auto variable when it is copied to the heap. The object type auto variable, which is modified by __weak, is not strongly referenced when a block is copied to the heap. __block functions: __block resolves the problem that the block cannot modify the value of the auto variable. __block cannot modify global and static variables, only auto variables. Because of what? After the block captures the auto variable decorated with __block, a member variable of the structure type pointer is added to the block structure. MRC/ARC and __block modify variables in many cases, MRC is not strong reference, arc is strong reference (block on the heap case). Be aware of circular references.Copy the code
10. Isa pointer
Added a just bit operations, | logic and, a is 1, the result is 1. Before the ARM64 architecture, ISA was a plain pointer to the addresses of class and metaclass objects. After the ARM64-bit architecture, it has been optimized to become a common body (Union) structure, which stores a lot of information, and uses a bit domain to store more information. This is one of the things you need to know about memory optimization. Structures in common structures have no real meaning, but are used to describe the role of each part of memory. Bits 1 to 61 are: Nonpointer :0 indicates a common pointer that stores the memory address of a class object and a metaclass object. 1 indicates that the pointer is optimized. Has_cxx_dtor: is there a c++ destructor? Is there a c++ destructor? Is there a c++ destructor? Is there a c++ destructor? Used when debugging to tell if an object is not fully initialized weakly_referenced: If there is a weak reference pointer to an object, no release faster EXTRA_RC: Stores the value of this reference count-1 has_sidetable: if it is not enough to store the reference technique, use the sidetable storeCopy the code
11, Class structure
The member variables isa, superClass,bits, cache are all members of the Class structure. Bits refer to class_ro_t at compile time and to class_rw_T at load time. The class_rT_T member refers to class_RO_T. Class_rw_t contains property information, method information, and protocol information. Class_ro_t stores name, member variable information, instanceSize, and so on. The method list stores method_t, which is a structure, and the members of the method structure have SEL name, types, IMP IMP, cache is a structure, Buckets is a hash table, bucket is a hash table, key (which stores SEL), value (IMP) is a member variable, and all methods that are called in the cache are stored in buckets. SEL&mask is used as index. After expansion, the cache (slightly different from the hash table) is emptied.Copy the code
Message sending, dynamic method parsing, message forwarding
Bit ->rw if there is no method, then binary search is used. If there is no order, then traversal search is used to find the base class. If there is no order, then judge whether the message recipient exists. Go there dynamic parsing (if without dynamic parsing), will distinguish metaclass object class object to call the instance and class respectively, if not through resolveInstanceMethod/resolveClassMethod to dynamically add method, Then mark it as dynamic resolution and re-send the message. If the dynamic adding methods go forward, whether forwardingTargetforseleto return values, it not nil called objc_msgsend, mehtodsignnatureForslet is nil, the return value is nil, Dose not.. Crash, not nil call forwardInvocaitonCopy the code
13, super
After compiling, look at the source code, override the parent method in the subclass, call super test, which is actually objc_msgSendSuper, again a message to self, just looking up from the parent class or method.Copy the code
14, atomic
Atomic is checked in the reallySetProperty method in the underlying implementation, and atomic is locked -> action -> unlock. The atomic base is os_UNfair_lock (this lock is almost the most efficient)Copy the code
15, file read and write security
In fact, the thread safety issue, this scenario is read and write lock solution. There are two ways to implement read/write locks on iOS: dispatch_barrier_async and pthread_rwlock.Copy the code
16, memory management – timer
CADisplayLink: the usage rate is the same as the screen refresh rate, both 60FPS. A common problem is the problem of circular references, where the viewController holds the displayLink, and the target of the displayLink holds the viewController, strongly holds each other. The solution is to use intermediaries to break the holding ring. Using the proxy (don't inherit NSProxy) implementation forwardingTargetForSelector that can be solved. NSProxy doesn't have any parent classes, it follows the <NSObject> protocol like NSObject, and NSProxy is the class that does message forwarding, and if it doesn't implement the target method itself, it immediately goes into message forwarding. Implement methodSignatureForSelector forwardInvocation can.Copy the code
17、 Tagged Pointer
After 64bit, mainly used to optimize NSNumber, NSDate, NSString small object data. There is no need to allocate memory dynamically. You can know data types and values directly from Pointers. The reason why multithreaded execution doesn't crash is because the bottom check is isTaggedPointer. If so, copy and release are not executed.Copy the code
Weak principle
Dealloc is an isTaggedPointer and isa is optimized. Has_assoc /has_cxx_dtor/ WeakLY_reference/has_SIDETABLE_rc are not directly released. If not, call object_disponse->destructInstance, determine whether there is a Cxxdtor and associated object, release it, and go to clearDeallocating. Clear the weak pointer of sidetable to nil if it is not optimized. If it is optimized to see if there are weak references or sidetable is used, go to clearDeallocating_slow. Weak_clear_no_lock is called to clear weak to nil.Copy the code
19, autoreleasePool
An automatic release pool is essentially a structure.Copy the code
20. Implementation principle of notification
Adding an observer before iOS9 is an unsafe_unretained reference. Exc_bad_access can occur after observer destruction, so remove the observer before observer destruction. After iOS9, it changed to a weak reference to the observer, so theoretically it doesn't matter if you don't remove the observer, but it's better to remove the observer in a generic way. After adding an observer through the notification center, an Observation object is created that stores the observer, SEL, and so on. NSNotification maintains the structure of GSIMapTable for storing observations, nameless, named, cache, nameless for storing observations that have no name, Named stores incoming named notifications; cache is used for quick lookups. Nameless and named are both hash tables. GSIMapTable object:observation object:observation named GSIMapTable has the following structure: name:mapTable Name :mapTable mapTable has the following structure: Object: Observation Object: ObservationCopy the code
Dynamic representation of OC runtime
Compile time is fine, and the corresponding method is executed at run time, which is called dynamic binding. Dynamic type: at runtime to determine the types of real objects Dynamic binding: a runtime dynamically add function calls, at run time to decide what to call method, what parameters need to preach in dynamic loading, loading executable code at run time and resources, such as the Retina device loading @ the pictures there are some integrated classification of 2 xCopy the code
22, The role of Runtime
1, exchange method, such as buried some methods such as viewDidLoad/viewWillAppear exchange; And check the NSArray NSDictionary/nsstrings inspected object when inserted into the object. Method swillzling (swillzling, swillzling, swillzling, swillzling, swillzling, swillzling, swillzling, swillzling, swillzling, swillzling, swillzling) 3. The exchange method should be placed in dispatch_once to ensure that the exchange method is only once, so as to prevent manual call +load method exchange back. 4.Copy the code
21, forwardingTargetForSelector for message forwarding, but in what is the difference between practical level
ForwardingTargetForSelector support only returns an object, meaning that the message can only be forwarded to an object forwardInvocation messages can be transmitted to any number of objects at the same timeCopy the code
23. What runloop does
1, thread alive, using run will always exist in memory, try to use run after method 2, handle screen refresh, recognize gestures, 3, autoreleasePool 4, network request 5, timer nstimer, Perform Selector 6, can detect the main thread of the delay detection runloop add observer, observe the state of the runloop switch. Beforewaiting andCopy the code
24. Principle of screen imaging
The CPU and GPU work together to draw the view into a buffer from which the video controller retrieves and displays it on the screen.Copy the code
25. When is layoutSubviews called
SetNeedsLayout layoutIfNeed is used to execute addSubView and to trigger layoutSubviews when the frame changesCopy the code
26, When will drawRect be called
When I call setNeedDisplay when I call sizeTofit and contentMode is set to Redraw, every time the frame changes it calls viewDidLoad of drawRect Controller, The view calls drawRect before displaying itCopy the code
27, wkwebview cookies
1, loadRequest into the request header (solve the first request cookie problem) 2, through the document.cookie set cookie (solve the same domain subsequent request iframe, Ajax) 3, 302 Redirecting cookie questions can be done by using decidePolicy's callback method to intercept 302 requests, copy request, and set cookies. (Still fails to resolve cookies for cross-domain requests)Copy the code
Optimization: list optimization, cold start optimization, memory optimization, installation package thin
List: 1, memory: use the check tool to see if there is a memory leak, instrument-? Leaks, or off-the-shelf integration tools. Power consumption: whether there are a lot of I/O operations, frequent network requests, real-time positioning, image rendering, CPU, GPU usage. Network optimization: use suitable transmission format, compress data; Start optimization with cache:Copy the code
The difference between instance methods and class methods
1. The storage structure of methods is different. Instance methods are stored in the class object structure, while class methods are stored in the metaclass structure. Instance methods can access member variables. 3, the class method can not call the instance method, you need to pass in the instance to call; 4. Instance methods can have the same name as class methods (reason 1)Copy the code
How to detect wild Pointers?
31, + class – the class
+class return self; -class return object_getClass(self) object_getClass(class object) returns a metaclassCopy the code
Do we need to release objects associated with the Runtime Associate method when the main object is dealloc?
No, the associated objects are released much later in their life than the objects themselves, in object_Dispose () method called by nsobject-dealloc. Can extensions add instance variables to compiled classes and power variables to classes created at run time? You cannot add instance variables to a compiled class. Because the compiled classes are registered with the Runtime, the linked list of objC_iVAR_list instance variables in the class structure and the memory size of the objC_iVAR_list instance variables are determined, so instance variables cannot be added to existing classes. Call the class_addIvar functionCopy the code
33. How to destroy singletons
GCD dispathc_once Remove the static dispatch_once_t token and set once_t to 0. Dispatch_once_t works because static decorations initialize it to 0 by default. Once's block is executed if and only if it is 0. If this function is executed, the dispatch_once_t static becomes -1 and is never executed. @synchronized +(instanceType)shareInstance {static id instance; @synchronized(self) { instance = [self alloc] init]; } return instance; }Copy the code
CALayer has three layer trees
Respectively presentTree(animation number)modelTree(modelTree)renderTree(render number) in the animation is presentLayer property values, the final display on the screen is modelTree property values.Copy the code
What is static?
The static keyword modifies functions and variables as follows: Hide static modified functions or variables. In this file, all functions after this statement are accessible. In other files, methods and functions are not accessible. A persistently static variable that can and can only be initialized once; Static modified variables are initialized to 0 by default;Copy the code
36, HTTP get/ POST differences
Get has limits on url length on specific browsers and servers, and in theory there are no limits. Get concatenates parameters to the END of the URL, which is unsafe. After TCP establishes a connection, the request header and data are directly sent to the server, which is faster than post. Post puts the parameters in the body of the request, sends the request to the server on the third of the three-way handshake, continues to send data to the server in response to 100 continue, and then 200OK.Copy the code
37. Why is the timer generated by GCD highly accurate?
Why refresh UI in main thread
Because UIKit is not thread-safe, multiple threads working on the UI at the same time can cause problems. Why not make it thread-safe? Thread-safe involves locks, which consume performance, affect processing speed and rendering speed. CPU, memory and other resources are relatively scarce on mobile devices, so UI operation is in the main thread. Normally the modifier generated by @property is nonatomic. Not to mention characters whose UI appears so frequently.Copy the code
39. Briefly explain the rendering mechanics
The Core of iOS rendering is Core Animation, and the rendering levels are as follows: layer number -> rendering tree -> rendering tree; Three stages: CPU stage (frame layout, preparation of view and layer hierarchy) OpenGL ES stage, iOS8 is changed to Metal (rendering service provided in the previous stage to color layers, generate various frames) GPU stage (perform a series of operations on the above operations, Finally appear on the screen. The CPU performs the frame layout and prepares the hierarchical relationship between the view and layer. The CPU will package the hierarchical relationship between the view and layer and submit it to the rendering service through IPC (inter-process communication). The rendering service will first hand the layer to OpenGL ES for texture generation and coloring, and generate the before and after frame cache. According to the hardware signal (VSync or CADisplayLink), it switches between the before and after frame cache. Finally, the required post frame cache is delivered to the GPU to collect pictures and shapes, exchange, apply texture mixing, and finally display on the screen.Copy the code
What is the difference between class_copyIvarList and class_copyPropertyList?
1. Class_copyIvarList: can get all properties in. H and. M and variables declared in curly braces. The obtained property names are underlined (except in curly braces). 2. Class_copyPropertyList: Only properties declared by the property can be obtained, including. M. Property names are not underlined.Copy the code
40, multi-threading where are these used (need to prepare a few)
A few questions about data structures
Basic data structures to master, such as: Array, linked lists, hash tables, heap, stack, tree sequence traversing binary tree after 1, 2, 3, the height of the binary tree to reverse chain, fast row 5, table 4 n steps, one can first can also take two order, how many kinds of six, four mice, 15 bottles, there is a bottle containing is poison, poison poisoning before one day, How did you know that bottle was poison in one dayCopy the code
Common sorting algorithm, sorting algorithm stable meaning, fast sorting complexity when degradation, basic order with what
Z word traverses binary tree, merges sort up steps, added a condition, this time up two steps, next time only up one stepCopy the code
43, implement string class, implement construction, destructor, which add a KMP (this later query)
44, Introduction to smart Pointers, where are the variables that hold reference counts, and whether reference counts are thread-safe?
45, the role of const keyword
Modifies variables to make them read-only and unmodifiable.Copy the code
46, The difference between a pointer and a reference? References can be null
1. In terms of memory, the system allocates memory space for Pointers, while objects referenced to bindings share memory space. Reference variables are not allocated. 2. After initialization, the pointer can change the object to which it points. The reference must be initialized at the time of definition, and the object cannot be bound after initialization.Copy the code
DNS resolution, the difference between recursion and iteration
How to learn technology at ordinary times, read what books, what output
What are the disadvantages? And why they left.
50, why memory alignment, memory alignment rules
Memory alignment helps speed up memory reading, and is an improvement in memory reading performance by swapping space for time. Rules: To be addedCopy the code
51. Process memory model
52. Inter-process communication
Virtual memory, why have virtual memory, virtual memory how to map to physical memory
Which memory space is shared by threads
Method for HTTPS clients to verify public keys
56, How to solve the memory leak in the code, how to implement the reference count of the smart pointer, which member functions affect the reference count
57, there is no thread safety problem in the code, thread safety problem will cause the program crash, why
58, lambda expressions, which apply variables outside the expression in ways and differences
What is the difference between decltype and Auto