This column will continue to update – iOS partners pay attention to!

(The answer is not unique, only for reference, the article has welfare at the end)

1. How to mix C and OC

Xcode recognizes several types of extension files:

  • .m file, can write OC language and C language code
  • .cpp: only C++ or C (C++ compatible with C)
  • .mm: mainly used to mix C++ and OC code, can identify OC,C,C++ code

2. How to call Swift and OC?

  • Swift calls the OC code

    You need to create aTarget-BriBridging-Header.hThe bridge file, in Joe file import need to call OC generation dock file can be
  • OC calls the Swift code

    Direct importTarget-Swift.hIf Swift needs to be called by OC, it needs to use @objc to modify the method or attribute

3. What are the differences between Foundation objects and CoreFoundation objects?

  • Foundation objects are OC, which requires manual memory management under MRC, but not under ARC

  • Core Foundation objects are C objects, and both MRC and ARC require manual memory management

  • Conversion between data types

    • ARC:__bridge_retained, __bridge_transfer(automatic memory management)
    • The ARC: __bridge

4. Compare with OC. What are the advantages of Swift?

Swift is a new language that borrows from JS,Python,C#,Ruby, etc. It looks scripted. Swift still supports the cocoa touch framework

Advantages:

  1. Swift is more secure, it’s a type-safe language.
  2. Swift is easy to read, with simple syntax and file structure.
  3. Swift is easier to maintain and has a clearer structure when files are separated.
  4. Swift has less code and a concise syntax that saves a lot of redundant code
  5. Swift is faster and performs better.

5. Delegate

Delegation is a form of agreement, which, as the name implies, entrusts someone else to do something for you.

delegate:

  1. Very strict grammar. All events to be heard must be clearly defined in the Delegate protocol, with clear syntax and easy to read.
  2. Compile warnings/errors occur if a method in the delegate is not implemented
  3. When releasing the proxy object, be careful to change the delegate to nil. If the setting fails, the call to the free object method will cause memory crash

6. Notification (notice)

There is a concept of a “Notification Center” in IOS app development. It is a singleton that allows some objects to be notified when an event occurs.

notification:

  1. Multiple objects can respond to a given notification, making the 1-to-many approach easy to implement
  2. The controller can pass the Context object (dictionary), which carries custom information about sending notifications
  3. It is difficult to track the application work and control process during debugging;

7.KVO

KVO is the ability of one object to observe the value of an attribute of another object and to detect changes in the value.

KVO:

  1. Provides a simple way to synchronize two objects. For example: synchronization between Model and View;
  2. The ability to respond to state changes of objects that we did not create, namely internal objects, without changing the implementation of internal objects (SKD objects);

8. How to select Delegate, Notification, and KVO?

All three patterns involve one object passing events to another object without coupling them.

  1. Delegate. One-on-one
  2. Notification one-to-many, many-to-many
  3. KVO one-to-one

The three have their own characteristics:

  • The delegate syntax is concise, easy to read, and easy to debug
  • Notification is flexible and can be used across multiple classes
  • KVO implements attribute listening, model and View synchronization
  • You can use different approaches depending on the scenarios you encounter in your actual development

9. If you were to design a notification center, what would it be?

Personal understanding: Refer to existing notification centers

  1. Create a notification center singleton class with a global NSDiction that holds notifications
  2. For classes that register notifications, take the name of the registration notification as the key, the method and class to execute, and some parameters as an array of values
  3. To send a notification, you can call the notification center, find the corresponding class and method through the dictionary key(notification name), and execute the call to pass the value.

10. Difference between Notification and KVO

  • KVO provides a mechanism to automatically notify responding observers when the properties of a specified object being observed are modified. KVC(key-value coding) is the basis of KVO
  • Notice: is a broadcast mechanism, in practice, through the notification center object, an object can be for all concerned about the object of this time sending messages, both are the observer pattern, different is the KVO is observed directly send a message to the observer, is direct interaction between objects, notice is the center for the both and notification object interaction, between objects The tao each other
  • Kvo is based on Runtime and has a notification center for notifications

11. What is the difference between a structure and an array?

  1. Structs can hold different types of elements, whereas arrays can only hold the same type
  2. Structure types need to be defined ourselves. An array is a different type plus the number of elements
  3. Structure memory allocation is very special, using the alignment principle, not necessarily the sum of the bytes of all elements, but the array must be the sum of the bytes of all elements.
  4. Struct Pointers can be pointer names -> struct element names (take elements); Arrays don’t work.

12. What is the implementation principle of NSDictionary?

  • Hash table (NSDictionary uses hash tables to map and store keys and values)

13. Talk about the differences between static and dynamic libraries

  • Static libraries: file name extensions are. A and. Framework.
  • Dynamic libraries: file names are.tbd(formerly.dylib) and.framework.
  • Static library: links are copied to executable files in their entirety, and multiple uses make multiple copies.
  • Dynamic library: do not copy when linking, the program is dynamically loaded into memory by the system when running, the system only loads once, multiple programs share (such as uiKit. framework of the system), saving memory.
  • A is a binary file that does not contain resources, so you need to add header files. Framework can contain header files and resource information

14. What are oc’s greatest strengths and weaknesses? What are the weaknesses and how do you get around them

Advantages:

  1. OC is a superset of C language, which adds object-oriented features on the basis of C language. It will be convenient and efficient to develop and use.
  2. Classes can quickly extend the methods of a class. Extension modules do not affect each other
  3. Runtime features, dynamic features (dynamic typing, dynamic binding, dynamic loading), improve programming flexibility
  4. OC can be co-written with C/C++

Disadvantages:

  1. Multiple inheritance is not supported, which can be compensated with classification, protocol, and message forwarding
  2. Operator overloading is not supported
  3. With dynamic runtime types, all methods are function calls, so many compile-time optimization methods, such as inline functions, are not used, and performance is poor.
  4. Less efficient than C, with weird syntax

15. What are the interaction modes between OC and JS?

  1. By blocking urls
  2. Using a MessageHandler (WKWebView)
  3. JavaScriptCore (UIWebView)
  4. Use WebViewJavascriptBridge library, can provide js to call OC, and OC to drop js

16. Call OC code (URL interception) through JS

  • By intercepting urls (for UIWebView and WKWebView)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *url = request.URL.absoluteString; If ([url rangeOfString: @rangeofString]. Location! = NSNotFound) {return NO; } return YES; }Copy the code

17. JS calls OC code (messageHander) ii

  • When the JS side wants to send some data to iOS, they call the following methods to send it.
  • Window. Its. MessageHandlers. < method name >. PostMessage (< data >) in the above code write complains JS end, cause behind the web business does not perform. This can be done using a try-catch.
  • Then the processing method in OC is as follows. It is the proxy method of WKScriptMessageHandler. Name corresponds to the method name in JS above.
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
Copy the code

18 JS call OC code (WebViewJavascriptBridge) three

1. Set the webViewBridge _bridge = [WKWebViewJavascriptBridge bridgeForWebView: self. WebView]; [_bridge setWebViewDelegate:self]; 2. Register the handler method, which needs to negotiate the method name with the preceding segment, which is used by JS to call Native. [_bridge registerHandler:@"scanClick" handler:^(id data, WVJBResponseCallback responseCallback) {// OC call NSString *scanResult = @"http://www.baidu.com" responseCallback(scanResult); }]; ResponseCallback :^(id responseData) {NSLog(@responsedata) {responseCallback:^(id responseData) {NSLog(@responseData); %@",responseData); }];Copy the code

19.OC calls JS code

NSString *jsStr = @" JS code executed "; [webView stringByEvaluatingJavaScriptFromString:jsStr]; / / use JavaScriptCore frame # import < JavaScriptCore/JavaScriptCore. H > - (void) webViewDidFinishLoad webView: (UIWebView *) { / / retrieve JS content in the webview JSContext * context = [webview valueForKeyPath: @ "documentView. Webview. MainFrame. JavaScriptContext"]. NSString *runJS = @" JS code executed "; [context evaluateScript:runJS]; }Copy the code

20. Have you ever encountered a BAD_ACCESS error? How do you debug?

The BAD_ACCESS error is a memory access error and can cause the program to crash. The error is caused by accessing wild Pointers (suspended Pointers).

  1. Set a global breakpoint to quickly locate the line of problem code.
  2. Enable zombie object diagnosis
  3. Analyze analysis
  4. Override the respondsToSelector method of an object to implement the last object accessed before EXEC_BAD_ACCESS appears.
  5. Xcode 7 has integrated BAD_ACCESS capture: Address Sanitizer. Usage: Select ✅Enable Address Sanitizer in the configuration box.

21. What is functional programming? The chain

  • Functional programming is a programming model that treats computer operations as functions in mathematics and avoids the concepts of states and variables. Functional programming is like a pipeline, a smooth solve the problem, from a starting point, one by one to call the function, because the last function has a return value is the tool class itself, so after the execution of a function, you can use a function to continue to call, a bit of chain thinking in it.
  • The most common thing we would like to do is functional programming, via objects. Method 1(). Method 2…..
[view mas_makeConstraints:^(MASConstraintMaker *make){     
make.top.bottom.left.right.equalTo(self.view);
}];
Copy the code

Chain programming?

  • Top, bottom, left, right. EqualTo (self. View) through “, “syntax, will need to perform continuous writing code, is called a chain programming, it makes the code easy to understand.

22. Responsive programming?

  • Responsive programming is a programming paradigm for data flow and change propagation.
  • For example, in an imperative programming environment, a:=b+c means assigning the result of an expression to A, and then changing the value of B or C does not affect A. But in reactive programming, the value of A changes as B or C changes.
  • Reactive Cocoa is a classic example of Reactive programming!

23. The difference between a Block and a Protocol. What problem is a Block used to solve?

  • “A common feature of a proxy and a block is a callback mechanism. The difference is that the proxy has more methods, more decentralized, common interface, more methods, and also uses a delegate to decouple
  • Code that uses blocks is more centralized and uniform, and asynchronous and simple calls back to blocks are better.”

What problems are blocks used to solve? Personal opinion:

  • Blocks are created for scheduling between multiple threads;
  • Block is also an OC object that can be passed as an argument, which is easy to use, simple, flexible, and requires very little code to implement code callbacks. There is a lot of code to negotiate

24. Talk about ios code signing

  • Ensure that downloaded apps from the App Store are not maliciously tampered with and cannot be installed if modified, and verify the identity of the app developer;

What is App Stochastic

App Stochastic can be translated as “Application Slim”. The App Store and operating system use a number of optimizations to minimize the size of the installation package when installing an App for iOS or watchOS, so that the App can be installed on your device at the minimum appropriate size. This process includes three processes: slicing, bitcode, and on-demand resources.

  1. Slicing can package corresponding app resource files
  2. Bitcode Apple will re-optimize binary apps containing Bitcode without submitting a new version of the app to the App Store.
  3. On-demand Resources are loaded On Demand

26. How to detect memory leaks and zombie objects without Instruments?

  • View MLeaksFinder source code analysis, domestic three parties

27. How do dictionaries work? How to quickly fetch value from 100W?

  1. NSDictionary uses hash tables to map and store keys and values. The design of hash functions affects the search and access efficiency of data.

    • (void)setObject:(id)anObject forKey:(id )aKey;
  2. NSDictionary in Objective-C is actually a hash table underneath, and in fact dictionaries in most languages are implemented through hash tables,

The essence of a hash table is an array, and each element in the array is called a bin, which holds key-value pairs. The length of the array is the number of boxes. Another important attribute of hash table is load factor, which is used to measure the degree of empty/full hash table and to some extent reflect the efficiency of query. The calculation formula is as follows: Load factor = total key-value logarithm/number of bins THE larger the load factor, the fuller the hash table, the more likely it is to cause conflicts, and the lower the performance. Therefore, in general, when the load factor is greater than a constant (maybe 1, 0.75, etc.), the hash table will automatically expand. Reference: https://zhuanlan.zhihu.com/p/394761790Copy the code

28. Relationship between isEquel and Hash

  1. IsEquel is used to compare two objects for equality. Unlike ==(address comparison), isEquel can be overridden to compare two objects
  2. Hash is a class method that can be called by any class and returns an NSInteger value. (If two objects are equal, they must have the same hash value. However, if two objects have the same hash value, it does not necessarily follow that they are equal.)

29. IsEquel and isEquelToString

  • IsEquel is comparing two NSObject methods,
  • IsEquelToString compares two string values for equality
  • IsEquel first compares the addresses of two objects and returns YES if they are the same. If they are different, it compares the object type and the value of the property. IsEquel is overridden to compare two objects

30. Notifications no longer need to be removed manually after iOS 9

  • Notifying NSNotification that the registrant needs to be removed manually when it is reclaimed has been a long-standing guideline. The reason is that in the MRC era, the notification center holds the unsafe_unretained pointer of the registrant. If the notification is not manually removed when the registrant is reclaimed, the pointer points to the reclaimed memory area and becomes an wild pointer. Sending a notification causes a crash. However, after iOS 9, the notification center holds the weak pointer of the registrant. Even if the notification is not manually removed, the pointer will be automatically empty after the registrant is reclaimed. Because there’s no problem sending a message to a null pointer.

31. How do I KVO NSMutableArray

  • In general, KVO is triggered only when a value is changed by calling the set method. But NSMutableArray’s set method is not triggered when it calls the addObject or removeObject family of methods. To implement KVO for NSMutableArray, we have the following methods:
@property (nonatomic, strong) NSMutableArray *arr; // Add element [[self mutableArrayValueForKey:@"arr"] addObject:item]; [[self mutableArrayValueForKey:@"arr"] removeObjectAtIndex:0];Copy the code

32. What the compilation process does;

* Objective,Swift are compiled languages. When a compiled language is executed, it must first generate machine code through the compiler. Machine code can be executed directly on the CPU, so the execution efficiency is high. OC, Clang + llvm. OC,Swift, Clang + llvm. OC, Clang + llvm. OC * iOS compilation, whether OC or Swift, uses Clang as the compiler front end and LLVM(Low Level Vritual Machine) as the compiler back end. Compiler front end: The compiler front end is responsible for: parsing, semantic analysis, and generating intermediate representation. During this process, type checking is done and any errors or warnings are flagged * Compiler back end: The compiler back end performs machine-independent code optimizations, generates machine language, and performs machine-specific code optimizations. LVVM optimizer does BitCode generation, link-duration optimization, etc. LLVM machine code generator generates different machine code for different architectures such as ARM64 etc.Copy the code

33. What fault tolerance do you pay attention to?

In collaborative team development, due to the different levels of each team member, it is difficult to control the quality of the code and ensure the robustness of the code. App crash and flash back often occur due to abnormal data returned from the background. In order to avoid such situation, it is particularly important to do some fault tolerant processing in the project. Greatly reduce the probability of crash and flash back due to data fault tolerance is not in place.

For example: 1. dictionary 2. array; 2. 3. Wild pointer; 4. AvoidCrash Github is a good ideaCopy the code

34. Have you done fault tolerance at the beginning of the project? How do I prevent interception from potentially crashing?

Example: 1. Category adds methods to classes to replace methods that might otherwise crash. Use the Runtime method swap technique to replace the system method with the new method added by the class. 3, the use of exception capture to prevent the crash of the program, and the corresponding processing. 4. Use the @try__catch__ method to intercept

Conclusion: 1, do not trust the server to return the data will always be correct. 2. In data processing, it is a good programming habit to carry out fault-tolerant processing and process data after corresponding judgment.

35.@try @catch exception mechanism

The @try block is used to catch exceptions. The @catch block is used to catch exceptions. — The purpose of each code block is: @try code block stores the code that may fail, @catch code block exception handling logic, @finally code block recycling resources; Syntax example:

try{ //.. Execute code that may have exceptions. Once an exception is found, it immediately jumps to catch execution. }catch(){//... }finally{//..}finally{//.. Finally} can be used to find bugs, or to debug, or to prevent crashes. OkayCopy the code

36. What are unit tests?

Unit testing refers to the examination and verification of the smallest testable units in software.

1. Unit tests can be logical/asynchronous/performance tests. 2. Unit tests are code tests. It's not tested by NSLog, it's tested by assertions, and the prejudgment condition has to be met. 3. You can write separate test case methods in your unit test class. These methods are similar to ordinary methods, but the method name must start with test and have no parameters, otherwise it will not be identified as a test method. 4. Not all methods need testing. For example, private methods do not need to be tested; only methods exposed to.h need to be tested. Generally, code coverage is around 50 to 70 percent. According to Github, YYModel test coverage is 83%, and AFNetworking test coverage is 77%, both of which are relatively high. Summary: Unit test can write some test cases for some key businesses according to the needs of the project, which can easily troubleshoot possible problems in business logic. It can also be easily tested and so on when making subsequent changes.Copy the code

37. If a project goes online and knows that this method may have problems, how can it be handled without destroying the method?

  1. Do some fault tolerance to prevent crashes
  2. Add some log collection, collect problems and then analyze them
  3. try_catch

38. A brief history of the Xcode compiler

Xcode3 previously: GCC; Xcode3: add LLVM, GCC(front-end) + LLVM(back-end); Xcode4.2: clang-llvm 3.0 becomes the default compiler Xcode4.6: LLVM upgraded to 4.2; Xcode5: GCC was scrapped, the new compiler was LLVM 5.0, and the transition from GCC to Clang-llVM was officially completeCopy the code

39. What is the process from code being pulled down from Git to.ipa generation, and what files are generated in the process?

  1. Git clone Remote address to local
  2. Pod tripartite integration
  3. Configure certificate information and signature
  4. Packaging of ipa

40. The principle of the Pods

  • Simple to understand: quickly search multiple third-party frameworks, and then automatically integrate multiple projects inside. And compile it into a static library of libpod. a for our project.

41. Difference between function pointer and Block

Similarities:

  • Both can be viewed as a snippet of code.
  • Both function pointer types and Block types can be used as types for variables and function parameters

Difference:

  • Function Pointers can only point to pre-defined blocks of function code, and the address of the function is determined when the link is compiled. From a memory perspective, a function pointer is simply a piece of executable code that points to a code area
  • A block is essentially an OC object, a subclass of NSObject, which is dynamically created in stack memory during program execution. You can send a copy message to it to copy the block object to the heap memory to extend its life cycle.

42. The symbol table

The symbol table generated when iOS is built is a mapping of memory addresses, function names, file names, and line numbers. The format is:

< start address > < end address > < function > [< file name: line number >]Copy the code

The stack information in Crash is all binary address information. If it is impossible to locate the problem using the binary address information, we need to restore the binary address information to the source code functions and line numbers, then the symbol table comes into play. Symbol table is used to restore the original Crash binary stack information into the source code file information containing line numbers, which can quickly locate the problem. The symbol table file (DSYM) in iOS is generated after the source code is compiled and Asset Catalog resources and info.plist files are processed. After the symbol table file (DSYM) is generated, the following steps, such as linking, packaging, signing, and verification, are carried out.

43. apply slim (Hillclimbing)

App Stochastic “App Slim”, a new feature released after iOS9. It can optimize the App Store and operating system when installing iOS apps to minimize the size of the package so that the App can be installed on your device in the smallest appropriate size. This process includes three processes: Slicing, bitcode, on-demand resources,

The appStore creates variations of the app based on the user's device model. These variations only contain the necessary parts of the executable structure and resources, and do not require users to download the full installation package. Automatically compile your app with the latest compiler and optimize it for your particular architecture. Instead of downloading app optimizations for different architectures, only device-specific optimizations are downloaded, making downloads smaller. For example, when a player unlocks a specific level of the game, they can download a new level (specific content related to that level). In addition, levels already passed by the player can be removed to save storage space on the device.Copy the code

44. Buried point treatment

What is a burial point? User behavior statistics, commonly known as buried point

Buried points are divided into two types:

  • Page statistics, that is, when entering the page and leaving the page, the time to stay on the page is counted
  • Interactive event statistics

Traceless burying point (automatic burying point) solution: Technical principle: Method-Swizzling

For a given event, UIControl calls sendAction:to:forEvent: to forward the behavior message to the UIApplication object, By the UIApplication object again to call its sendAction: to: fromSender: forEvent: method to distribute the message to the specified target, so we write a UIControl category, This is done by replacing its sendAction:to:forEvent: method with a locally configured buripoint JSON or plist file (if buripoints require additional parameters, add attributes to the UIControl category via Runtime).

45. Talk about APNS in iOS, the principle of remote push?

Apple Push Notification Service (APNS) is Apple’s remote Notification push. The principles are as follows:

  1. The iOS system requests the mobile phone from the APNS serverdeviceToken
  2. The App receives the deviceToken from the mobile phone and sends the token to the App server.
  3. The App server needs to send push messages through the APNS server
  4. It is then sent to the corresponding mobile phone based on the corresponding deviceToken

Recommended reading: If you want to enter a big factory, the interview questions are essential! (iOS Interview collection!)

An iOS developer learning path guide

Next entry:IOS Interview: OC Bottom (3)