Interview questions on IOS of various companies in Beijing, Shanghai, Guangzhou, Shenzhen and Hangzhou

Interview voice

Recently, when preparing for the interview, I reviewed some projects and knowledge points I had written in the past, looked at the code and problems again from the perspective of the underlying and principles, and found many interesting places!

If you think the questions are good, it’s worth learning when you are preparing for the interview. You have read a lot of interview questions before, and feel that they are not enough or too redundant. So I deleted and rearranged some interview questions on the Internet, and now I will share them with you!!!

It collects and sorts out some IOS related questions, most of which are used by large and small factories for interviews or interviews with other people. It can hit most of the interviews and daily work. I hope you can use it to test yourself

Electronic answer:

Because the answer is too many, I made a PDF document, because the short book cannot upload the file, needs the answer to be able to add the small edition myIOS communication group761407670. The password “000” is used to obtain documents. Recruiters are welcome to come to work and provide a bigger platform

1. Given a string, output the position of the first character that appears only once in the string? For example, “abaccddeeeef” is B, and the output is 2

A: int main ()


char a[80] = “abaccddeeef0”;

char ch;

int i, m, b[80];

int flag = 0;

Ch = getchar(); / / get a character

m = strlen(a);

for (i = 0; i < m; ++i){

If (a [i] = = CH) {/ / if it is found, judge whether it is equal directly

B [flag] = I + 1; / / record position

flag += 1;



if (flag == 0)printf (“no”);

else {

printf (“%dn”, flag);

For (I = 0; I < flag; I + +) {/ / output the position with a loop

printf (“%d “, b[i]);


printf (“n”);


return 0;


2. Implement a bubble sort or quick sort

A: bubble sorting:

intarray[5] = { 28,27,36,45,8};

for (int i = 0; i < 4; i++) {

for(int j = 0; j < 4; j++) {

if (array[j] > array [j + 1]){

int temp = array[j];

array[j] = array[j + 1];

array[j + 1] = temp;


for(int i = 0; i < 5; i++) {


3. Please write a function to calculate factorial

A: int f (int i)




return t;


4. Cocoa touch provides several cores

Animation transition class?

A: cocoa touch offers four types of cores

The animation transition types are: cross fade, push, display and overlay.

5. How does IOS platform do data persistence? Is coredata related to SQLite? Is coredata a relational data?

A: data persistence is essentially writing files, but logically it can be divided into many kinds, such as writing to sandbox, such as saving to the network, such as writing to database.

Core data is the encapsulation of SQLite, because SQLite is the API of C language. However, some people also need the API of obj-c, so there is core data. In addition, core data not only translates the API of C into the API of OC, but also provides some management functions, which is more convenient to use.

After the app is upgraded, changes in database fields or tables will cause version management and data migration of crash and coredata to become very useful. It is still troublesome to manually write SQL statements.

The combination of coredata and icloud is also very good. If there is a need in this respect, coredata will be given priority.

The coredata does not directly manipulate the database. For example, when using coredata, the primary key of the database cannot be set. At present, manual operation is still required.

6. Can Object-C classes be inherited multiple times? Can multiple interfaces be implemented? What is category? Is it better to rewrite a class by inheritance or classification? Why?

A: class of Object-C cannot be inherited in multiple ways; multiple interfaces can be implemented, and multiple inheritance of C + + can be completed by implementing multiple interfaces; category is a category, and generally, the method of using category to rewrite a class is only effective for this category, and it will not affect the relationship between other classes and the original class.

7. What’s the difference between import and include ,@class What’s the difference between “import < > and” import “?

Answer: ාimport is the keyword of Objective-C import header file, andාinclude is the keyword of C / C + + import header file, If you use the ා import header file, it will be automatically imported only once, and will not be imported repeatedly, which is equivalent to ා include ‘and ා pragma once; @ class tells the compiler to view the implementation file of a class only when it is executed, so as to solve the mutual inclusion of header files; # import < > is used to contain the system header file, while the ා import “# is used to contain the user header file.

8. What are the functions of the attributes readwrite, readonly, assin, retain, copy, and nonautomatic, and under what circumstances?

A: readwrite is a read-write feature; when you need to generate getter methods and setter methods

Readonly is a read-only feature that only generates getter methods, not setter methods; you don’t want properties to change outside the class

Assign is an assignment property, and the setter method assigns the input parameter to the instance variable;

Retain indicates that the property is held. The setter method will reserve the incoming parameter first and then assign a value. The retaincount of the incoming parameter will be + 1;

Copy means the copy feature, and the setter method copies the incoming object; when a new variable needs to be completely copied.

Nonatomic operations determine the setter generated by the compiler

Whether the getter is an atomic operation. Atomic means multi thread safety. Generally, nonatomic is used

9. Write a setter method to complete @ property (nonatomic,

retain)NSString Name; writes a setter method to complete the @ property (nonatomic, copy) nsstringname;

Answer: – (void) setname: (nsstring *) str


[str retain];

[name release];

name = str;


  • (void)setName:(NSString *)str


id t = [str copy];

[name release];

name = t; }

10. For the statement nsstring * obj=

[[nsdata alloc] init]; what type of object is obj at compile time and run time, respectively?

Answer: at compile time, it is of type nsstring; at runtime, it is an object of type nsdata

11. Currently programmed function: int

Rand100 (). This function can return 0 ~ 99 random integer, and can guarantee equal probability. Please use this function to realize int Rand 10000 (), and require equal probability to return 0 ~ 9999 random number. (other system functions are not allowed)

12. Tom is going to hold a party at home now. Although he has a lot of chopsticks, the length of these chopsticks is not exactly the same. First, we should know the length of each chopstick, and require each guest to get two chopsticks of the same length

, find the maximum number of guests that can be invited

Programming implementation: int getmax (int arrlength [n])

13. For an existing sequence of integers, you can exchange any two of them to get a new sequence. How many possible results can be obtained in total

Programming implementation: int gettotal (int arrorigin [n])

14. There is an array of M rows and N columns, which requires the installation of reverse diagonal (top right to bottom left) to print the array. Programming implementation: intprintmatrix arrmatrix [M]

The following example prints in the following order:




8910 11

15. In UIKit, the relationship between frame and bounds is (c)

A. Frame is an alias for borders

B. Frame is the inheritance class of bounds

C. The reference frame of frame is the coordinates of parent graph, and the reference frame of borders is its own

D. The reference frame of frame is its own coordinate, and that of bounds is the coordinate of parent graph

16. The incorrect function of a class’s delegate is (d)

A. Functions in delegate are implemented in other classes

B. It is mainly used for one-to-one message transmission between different types of objects

C. If there is no assignment, it will not be triggered

D. You can delegate an object to multiple objects of other types

17. The following description of Objective-C memory management is wrong (a)

A. When using arc to manage memory, the retain and dealloc methods of the object are not called

B. The autoreleasepool releases the allocated objects in the drain

C. When using arc to manage memory, allocating a large number of objects in threads without autorelease pool may cause memory leakage

D. Nszone cannot be used in projects that use arc

18. The correct definition of block below is (a)

A.tyoedef void(^SuccessBlock)(BOOLsuccess);

B. tyoedef void(^SuccessBlock)(NSStringvalue,BOOL success);

C. tyoedef void^(SuccessBlock)(NSStringvalue,BOOL success);

D. tyoedef void^(SuccessBlock)(NSString*value);

19. Uibutton inherits from subclass to parent class once from: (d)

A. UIView-> UIViewController->UIController

B. UIResponder-> UIControl-> UIView

C. UIControl-> UIResponder->UIViewController

D. UIControl-> UIView-> UIResponder

20. The following is an incorrect description of the use of class methods in IOS development: (c)

A. Class methods can call class methods

B. Class methods cannot call instance methods, but class methods can access instance methods by creating objects

C. Class methods cannot use instance variables, including self

D. Class methods can be sent to classes or objects as messages

31. Under what circumstances are the keywords weak and assign different?

A: assign pointer is assigned without reference counting operation. If it is not set to nil after use, it may generate a wild pointer. Once weak is not used, it will never be used, and it will not generate a wild pointer!

32. Can Object-C classes inherit multiple objects? Can they implement multiple interfaces? What is category? Is it better to override a class method by inheritance or classification? Why?

A: class of Object-C cannot be inherited in multiple ways; multiple interfaces can be implemented, and multiple inheritance of C + + can be completed by implementing multiple interfaces; category is a category, and generally, the method of using category to rewrite a class is only effective for this category, and it will not affect the relationship between other classes and the original class.

32. How to test performance with IOS devices?

A: profile > instruments > time profiler

33. What do we mean by OC is dynamic runtime?

Answer: polymorphism. It mainly delays the determination of data type from compile time to runtime. This problem involves two concepts, runtime and polymorphism. In short, the runtime mechanism allows us to determine the class of an object and call the specified method of the class object until runtime. Polymorphism: the ability of different objects to respond to the same message in their own way is called polymorphism. That is to say, suppose that all the life classes have the same method eat; that is, humans belong to creatures, and pigs belong to creatures. After inheriting life, they can implement their respective eat, but the call is that we only need to call their respective eat methods. That is, different objects respond to the same message in their own way (responding to the eat selector). Therefore, it can be said that the runtime mechanism is the basis of polymorphism.

34. When do you choose GCD and nsoperation for your project?

A: the advantage of using nsoperation in a project is that nsoperation is a highly abstract thread. Using it in a project will make the program structure of the project better. The design idea of subclassing nsoperation is that it has the advantages of object-oriented (reuse and encapsulation), so that the implementation is supported by multithreading, and the interface is simple. It is recommended to use it in complex projects. The advantage of using GCD in a project is that GCD itself is very simple and easy to use. For uncomplicated multithreading operations, it will save the amount of code. The use of block parameter will make the code easier to read. It is recommended to use it in simple projects.

35. Is the file read input stream or output stream?

When something is read into memory, it is an input stream. When something is written from memory to a record storage output stream, we start from the record storage. All of us will feel puzzled The direction of IO flow can be divided into input stream and output stream. Input stream reads resource data into buffer buffer, while output stream writes data in buffer buffer to a specified location according to specified format. Therefore, it is meaningful to use these two streams at the same time. For example, if you want to upload a file, you need to use the input stream to read the file to be uploaded into the buffer, and then use the output stream to write the file to a location on the network server, then the upload is successful; if the file is downloaded, the input stream is first obtained to read a file in the network server, and then the output stream is used to write to a local file; and for example, the copy of the file is also It is a good example to read with input stream and then write it out with output stream. You can try a small example first to help you understand java io

36. Briefly describe the relationship between calayer and uiview

A: uiview and calayer are interdependent. Uiview relies on the content provided by calayer, which relies on the container provided by uivew to display the drawn content. In the final analysis, calayer is the foundation of all this. Without calayer, uiview itself will not exist. Uiview is a special calayer implementation, adding the ability to respond to events.


Uiview comes from calayer, which is higher than calayer. It is a high-level implementation and encapsulation of calayer. All features of uiview come from calayer support.

37. Declare a static method and an instance method

A: let’s talk about instance methods. When you write a method to a class, if the method needs to access the member variables of an instance, then define the method as an instance method. An instance of a class usually has some member variables, which contain the state information of the instance. This method needs to change these states. Then the method needs to be declared as an instance method.

Static methods, on the contrary, do not need to access the member variables of an instance. They do not need to change the state of an instance. We define this method as a static method.

38. What are the common data types of Object-C and what are the differences between them and CD?

A: the data types of Object-C include nsstring, nsnumber, nsarray, nsmutablearray, nsdata, and so on. These are classes. After creation, objects are created. The basic data type of C language, int, is only a certain byte of memory space for storing values. The nsnumber of Object-C contains the methods of parent nsobject and nsnumber itself, which can complete complex operations.

39. What are the animation effects of uiview

For example, uiviewanimationoptioncurveeaseinout







40. Do you know about SVN, CVs and other version control tools?

A: I understand

41. Static link library

A: static library is a collection of program code and a way to share code

Static library is the existence form of closed source. A and. Framework

When connecting, the static library will be completely copied to the executable file. If it is used repeatedly, there will be redundant copies, which is equivalent to the jar package in Java. Some classes are compiled into a package. If you import this file in different projects, you can use the classes in it,

42. What is a sandbox model and what operations are private APIs?

A: 1. The application can operate in its own sandbox, but it cannot access the sandbox of any other application.

2. Data cannot be shared between applications, files in sandboxes cannot be copied to other application folders, and files in other application folders cannot be copied to sandboxes.

3. Apple forbids any reading and writing of files outside the sandbox, and apps are forbidden to write content to folders outside the sandbox.

4. There are three folders in the root directory of sandbox: documents. Generally, the application data files should be saved in this folder to store user data or other information that should be backed up regularly. There are two folders under library. Caches store the information needed to restart the application. Preferences contains the application preferences file, but do not modify the preferences here. Temp is used to store temporary files, which are unnecessary files when the application starts again.

There are three folders in the root directory of sandbox: documents, TMP, and library.

1. Documents directory: you should write all de application data files to this directory. This directory is used to store user data or other information that should be backed up regularly.

2、 Directory: This is the package directory for the application, which contains the application itself. Because the application must be signed, you cannot modify the contents of this directory at run time, otherwise the application may fail to start.

3. Library Directory: there are two subdirectories under this directory: caches and preferences

Preferences Directory: contains the preferences file for the application. Instead of creating preferences files directly, you should use the nsuserdefaults class to get and set preferences for your application

Caches Directory: used to store application specific supporting files and save the information needed in the process of application restart.

4. TMP Directory: this directory is used to store temporary files and save information that is not needed during application restart.

Several ways to obtain directory in IOS sandbox:

//Get sandbox home directory path

NSString *homeDir = NSHomeDirectory();

//Get documents directory path

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *docDir = [paths objectAtIndex:0];

//Get caches directory path

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

NSString *cachesDir = [paths objectAtIndex:0];

//Get TMP directory path

NSString *tmpDir = NSTemporaryDirectory();

//Get a picture resource in the current package( apple.png )Path

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];

UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];


NSFileManager* fm=[NSFileManagerdefaultManager];

if(![fm fileExistsAtPath:[selfdataFilePath]]){

//The following is how to save the file

[fm createDirectoryAtPath:[selfdataFilePath] withIntermediateDirectories:YES attributes:nil error:nil];

//Get all the file names in a directory

NSArray *files = [fm subpathsAtPath: [selfdataFilePath] ];

//Read a file

NSData *data = [fm contentsAtPath:[selfdataFilePath]];


NSData *data = [NSDatadataWithContentOfPath:[self dataFilePath]];


43. What is the agreement and what is its function?

Protocol: declares a series of methods that can be implemented by any class, even if the classes that comply with the protocol do not have a common superclass. Protocol methods define behavior independent of any particular class. Simply put, a protocol defines an interface that other classes are responsible for implementing. If your class implements a protocol method, it is said that the class follows this protocol.

The role of the agreement:

1. Define a set of common interfaces (public)

@Required: methods that must be implemented

@Optional: optional implementation methods (none of them can be implemented)

2. Delegate value transfer:

It is a design pattern in itself. It means to delegate something to someone else.

For example, for the value transfer between two classes, class a calls the method of class B, and class B notifies class a of problems encountered in the execution process. At this time, we need to use a proxy.

Another example: when the value transfer between the controller and the controller jumps from C1 to C2, and then returns from C2 to C1, C1 needs to be informed to update UI or do other things. In this case, we use the delegate to transfer values.

44. How do you detect memory leaks when developing large projects?

You can use Xcode’s built-in tool run — start with performance tool, which has a leaks tool under instruments,

After starting the tool, run the project, the tool can display the memory leak situation, double-click to find the source location, which can help to deal with the memory leak.

45. Have you ever implemented a framework or library for others to use? If so, please talk about the experience of building a framework or library; if not, please imagine and design the framework’s public API, and indicate how to do it and what aspects need to be paid attention to, so that others can easily use your framework

46. App from application creation to launch (Appstore)

Before you start submitting the program to the app store, you need to have an app ID, a valid publishing certificate, and a valid provisioning profile.

On the website of itunesconnect, create app application, set corresponding information, upload app package file, and submit it for approval

47. Programming Fibonacci sequence: int f (INTN) with your familiar voice;

Recurrence formula of Fibonacci sequence f (n) = f (n-1) + F (n-2)

F(1) = 1

F(2) = 2

F(3) = 3

F(4) = 5

F(5) = 8

int F(int n){

if(n == 1){



return f(n-1)+f(n-2);


48. Given two ordered arrays a and B, write a function to find their common element: findcommon (a,

B) And list other possible search methods, the more the better

For example:

Array A = [1, 3, 5, 6, 9]

Array B = [2, 3, 6, 8, 10]

Return result = [3,6]

void FindCommon(int a, int b, int n)


int i = 0;

int j = 0 ;

while(i < n && j < n){

if (a[i] < b[j])

++i ;

else if(a[i] == b[j])


cout << a[i] << endl ;

++i ;

++j ;


else// a[i] > b[j]

++j ;


51. How to realize KVO?

A: KVO: the mechanism to allow the object to receive notification when the properties of the specified object are modified.

52. How to assign a private property to an object?

Answer: use KVC namely key value code to assign value to private property of object

53. What’s the essence of block? Why should the value of external variables be changed in the block_ Block modification, add_ What is the principle of block modification?

A: (1) block is essentially a data type, which is mostly used for parameter passing instead of proxy method (if there are multiple parameters to be passed or multiple proxy methods need to be implemented or the proxy method is recommended), it is rarely used as return value. Block is an OC object, whose function is to save code fragments, prepare code in advance, and execute it when necessary

(2) Because the use of block code blocks may cause internal circular references, it should be decorated before the block definition

54. Under what circumstances will block cause circular reference and how to solve it?

Answer: (1) analyze the problem of circular reference from two aspects

When self owns a block, self’s method (or a property owned by self) is called in the block. Form you have me, I have you, this will cause circular reference

If an instance variable is changed into a local temporary variable, the strong reference will directly point to the local temporary variable, but the local temporary variable will be released quickly, so the first case is generally considered

(2) Solution: modify the block__ Weak (ARC) or__ block(mrc)

55. Under what circumstances does nsurlsession have the problem of circular reference and how to solve it?

A: (1) when using nsurlsession to sign its proxy, there will be a circular reference problem, because the proxy is a retain strong reference

(2) Solutions

(1) After the download is completed, cancel the nsurlsession session and release the session, which is assigned as nil.

(2) Do the same when the view is about to disappear. In order to prevent jumping to the controller without downloading.

The details are as follows:

* * When the view is about to disappear, cancel the session_/

  • (void)viewWillDisappear:(BOOL)animated



//Task complete, cancel the nsurlsession


//Release session

self.session =nil;


56. How to implement get cache?

Answer: 1. Use get to request data

2. The IOS system SDK has done a good job of caching. All you need is to set the memory cache size, disk cache size, and cache path. The code is as follows

NSURLCache urlCache = [[NSURLCache alloc] initWithMemoryCapacity:4 1024 1024 diskCapacity:20 1024 * 1024 diskPath:nil];

[NSURLCache setSharedURLCache:urlCache];

57. In the process of using SQLite, if multiple threads operate the same database at the same time, what problems will be caused and how to solve them?

Answer: (1) easy to cause system crash

(2) Solution: turn on the third serial mode and use a class (singleton mode) operationdatabase

58. If a JSON format data is submitted to the background server and the background server returns a piece of common text, how to implement it with nsurlconnection / nsurlsession / AFN respectively?

A: 1. Sending a request using nsurlconnection is very simple

(1) Create an nsurl object and set the request path (set request path)

(2) Pass in the nsurl, create an nsurlrequest object, set the request header and request body (create the request object)

(3) Send nsurlrequest using nsurlconnection

2. The steps of sending a request using nsurlsession are very simple

1) Determine the request path (usually provided by the company’s background developers in the form of interface documents), and get request parameters are directly followed by the URL

2) Create a request object (the default includes the request header and request method [get]). This step can be omitted

3) Create session object (nsurlsession)

4) Create a request task based on the session object (nsurlsession datatask)

5) Task execution

6) After getting the response from the server, parse the data (XML | JSON | HTTP)

59. Please describe the internal implementation principle of sdwebimage

A: the underlying implementation of sdwebimage has sandbox caching mechanism, which is mainly composed of three parts

1. Memory image cache

2. Memory operation cache

3. Disk sandbox cache

60. What do you know about runtime? Have you ever used runtime in the implementation and development process or in the third-party framework you use? If so, please describe its internal implementation mechanism

A: Runtime:runtime Is a set of relatively low-level pure C language API, belongs to a C language library, contains a lot of low-level C language API. In the OC code we usually write, when the program is running, it is actually converted into the C language code of runtime, and runtime is the behind the scenes worker of OC

( in the website: in fact, they are all converted into the C language code of runtime.)

61. How do threads communicate?


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

//Download pictures

UIImage *image = nil;


//Back to main thread


(2) Thread communication of nsthread

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

//Download pictures

UIImage *image = nil;

[selfperformSelector:@selector(settingImage:) onThread:[NSThread mainThread]withObject:image waitUntilDone:YES modes:nil];


This also applies to communication between child threads.

62. How to solve the problem of repeated requests for the same network address in the network image processing problem?

Answer: using the dictionary, the image address is key, and the download operation is value

63. How to realize the bottom layer of automatic release pool?

A: the auto release pool is implemented in the form of stack: when you create a new auto release pool, it will be added to the top of the stack. When an object receives the auto release message, it will be added to the current thread’s auto release pool at the top of the stack. When the auto release pool is collected, they will be deleted from the stack, and all objects in the pool will be released once

64. Exchange the values of a and B in two ways without intermediate variables

A = A+B;

B = A – B;

A = A – B;

65. Briefly describe the client caching mechanism?

You can’t understand the answer

66. What is the lifecycle and related functions of controller view? How do you use it in development?

1. call viewWillAppear before the view is displayed; the function can be called many times.

2. After the view is displayed, call viewdidappearance;

3. call viewWillDisAppear before the view disappears; the function can be called many times, if necessary.

4. Before and after layout changes, call viewwill / didlayoutsubviews to process relevant information;

67. The implementation mechanism of nsrunloop and how to use it in multithreading?

Answer: nsrunloop is the processing mode of IOS message mechanism

The main function of nsrunloop is to control the execution and sleep of threads in runloop. When something is done, the thread controlled by nsrunloop will work. If there is nothing to do, the control thread of current runloop will sleep

2. Runloop is to detect the asynchronous time of inputsource (such as click, double-click and other operations) from the thread start to the thread end, and detect the timesourse synchronous event. When the input source is detected, the processing function will be executed, and the notification will be generated first. The core function adds runloop observers to the thread to listen for the event, which is intended to handle when the event occurs.

3. Runloopmode is a collection, including listening: event sources, timers, and runloop servers to be notified

1. Only when creating secondary threads for your program, you need to run run run loop. For the main thread of the program, run loop is the key part. Cocoa provides the code to run the main thread run loop, which also runs the run loop automatically. The run method in the IOS program uiapplication will start the run loop when the program starts normally. If you create a program using the template provided by Xcode, you never need to start the run loop yourself

2. In multithreading, you need to judge whether you need run loop. If you need a run loop, you are responsible for configuring the run loop and starting it. You don’t need to start the run loop under any circumstances. For example, if you use threads to handle a predefined, time-consuming task, you don’t need to start a run loop. Run loop is only needed if you want to interact with threads

68. Briefly describe the startup process of app, starting from the main file

Enter the main function and execute uiapplicationmain in the main function of main. M, which is the entry point of IOS program!

int UIApplicationMain(int argc, char argv[], NSString principalClassName, NSString *delegateClassName)

Argc, argv: parameters of ISO C standard main function, which can be directly passed to uiapplicationmain for relevant processing

Principalclassname: Specifies the application class, which must be uiapplication (or subclass). If nil, the uiapplication class is used as the default value

Delegateclassname: Specifies the proxy class of the application class, which must comply with the uiapplicationdelegate protocol

This function creates uiapplication object according to principalclassname, creates a delegate object according to delegateclassname, and assigns the delegate object to the delegate attribute in uiapplication object

The liuapplication object will send different messages to the delegate object in turn, and then establish the main runloop (event loop) of the application to process the event (the AP of the delegate object will be called first) plication:didFinishLaunchingWithOptions )

This function returns only when the program exits normally. If the process is forced to be killed by the system, the process is usually terminated before the function returns

69. How do you use the third party API?

Cocoa pod import

70. Declare a constant with the preprocessing instruction ාාාාාාාාාාාාාාාාාාා

A: define second 365_ 24_ 60*60

91. Which agents does uitableview need to implement? List the functions that must be implemented in uitableview proxy and some other commonly used functions


-( NSInteger )tableView:( UITableView *)tableViewnumberOfRowsInSection:( NSInteger)section;

How many lines are there in a group

-( UITableViewCell )tableView:( UITableView )tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath;

The above two methods must be implemented for the cell in each row

Commonly used are

  • ( void )tableView:( UITableView _)tableViewdidSelectRowAtIndexPath:( NSIndexPath_)indexPath

Select later event settings

-( CGFloat )tableView:( UITableView _)tableViewheightForRowAtIndexPath:( NSIndexPath_)indexPath

Set the height of the cell


92. How to develop an application on IOS?

A: first of all, there must be a MAC system (buy an apple computer, apple book or macmini). Without this condition, you can install a black apple mac system or a virtual machine. Then install an x-code development environment. If you learn IOS development, these are OK. If you want to develop and go online, you have to prepare iPhones / iPods and iPads as test machines, and apply to apple for a developer account with an annual fee of $99. And then you can develop your program. After the development is completed, publish it to the app store and pass the audit.

*93. Mixed use of C + + and Objective-C

//No answer or C + + java

A. CPP files can only use C / C + + code

B. In the header file of cpp file include, Objective-C code can appear

C. Mm file mixed CPP can be used directly

D. The key of CPP using Objective-C is to use interface, not code directly

*94. Which of the following code does not throw an exception (C & D)

A. NSArray _array = @[1, 2, 3];NSNumber_number = array[3];// @[@1,@ 2,@ 3]

B. NSDictionary *dict = @{@”key”:

Nil}; / / value cannot be empty

C. NSString str = nil; NSString str2 =[str substringFromIndex:3];

D. NSString str = @”hi”;NSString str2 =[str substringFromIndex:3];

*95. To switch from one viewcontroller to another without navigationcontroller, you should ()

A.{self.navigationControllerpushViewController:nextViewController animated:YES};

B.{self .viewaddSubview:nextViewController}

C. {selfpresentModalViewController:nextViewController animated:YES};

D. {selfpushViewController:nextViewController animated:YES};

Analysis: both a and C need navigationcontroller. B, the view of one controller cannot load the view of another controller, so select c!

*96. The following thread management errors are ()

//Not sure

A. GCD manages a thread pool on the back end

B. The nsaperation queue is a higher-level encapsulation of nsthread

C. Nsthread needs to manage its own thread life cycle

D. GCD can assign threads according to different priorities

*97. Data persistence in IOS (d)

A. Property list

B. Object archiving

C. SQLite and coredata

D. All above + object Archive

98. It has the following macro definitions:


defineY(n)((N + 1) * n)

Then the execution statement: Y (5 + 1) is: (26)

Use “blue” to indicate the error

//Not sure

char *GetBlue()


char *pcColor;


pcColor = “blue”;

pcNewColor =(char*)malloc(strlen(pcColor));

strcpy(pcNewColor, pcColor);

return pcNewColor;


A: strcpy is a string copy function. Its function prototype is strcpy (char)dst, cT char * SRC); copy a string starting from SRC into the memory at the beginning of DST, and the end flag is’ 0 ‘. Since the length of the copy is not controlled by us, it is easy to make mistakes in this string copy

100. What are the common data types of Object-C and what are the differences between them and the basic data types of C? For example, nsinteger and int

A: the data types of objects include nsstring, nsnumber, nsarray, nsmutablearray, nsdata, and so on. These are all classes. After creation, they are objects. The basic data type of C language, int, is only a certain byte of memory space for storing values. Nsinteger is the basic data type, not a subclass of nsnumber or nsobject. Nsinteger is an alias for the basic data type int or long (the definition of nsinteger is typedef long nsinteger). The difference is that nsinteger will decide whether it is int or long according to whether the system is 32-bit or 64 bit

101. Does IOS have a garbage collection mechanism? How does it work?

A: OC supports garbage collection (GC). However, in Apple’s mobile terminals, GC is not supported. In MAC desktop system development, GC is supported

Mobile terminal development supports arc (automatic

Arc is a new technology introduced after ios5. Its mechanism is different from GC. When we write code, we don’t need to send release or autorelease method to the object, and we can’t call delloc method. The compiler will automatically generate release message (autorelease) to the user in the appropriate position. The feature of arc is that the automatic reference technology simplifies the difficulty of memory management

102. Please use GCD to complete the following tasks, execute concurrent task Task1, and update UI after Task1 is completed


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{


Nslog (@ “execute Task1”);

//Update UI

dispatch_async(dispatch_get_main_queue(), ^{

Nslog (@ “update UI”);



103. Why update the UI in the main thread? What do you do if you want to update the UI in a child thread?

Answer: (1) UI cannot be updated in the child thread. Except for a few UI, other UI updates should be returned to the main thread after the execution of the sub thread. If the sub thread is running all the time, the main thread cannot know the function stack of UI update in the sub thread, that is, the UI cannot be updated;

(2) Return to the main thread for UI update;

104. How to implement a tableview through storyboard

The key step of customizing cell

A: first, create your own custom cell class, which we call customcell, and inherit from uitableviewcell. Define the control you need in this class.

Then, open the storyboard and select the uiviewcontroller to which you want to add a custom cell. We call it viewcontroller. Add a cell (or modify the original cell) in uitableview. Change the style of the cell to custom, the class of the cell to customcell, and the identifier to the customcellidentifier. You can then add a control to the cell to connect the control with the one you just defined in customcell.

Finally, in view controller’s uitableview tableView:cellForRowAtIndexPath : add the following code to the proxy method:



In this way, a cell is created, and the control you add can be set after this code.

105. How to generate a general static library supporting multiple architectures (simulator, ARM7, arm64) at the same time?

A: valid architectures is set to armv7 armv7s arm64 i386 x86_ 64;

Architecture settings remain unchanged (or as you need): armv7 arm64;

Then choose IOS device and emulator to compile, finally find the related. A for package, and use the path simulator Library of Lipo – create real machine library. A’s path – output composition Library’s name;

In this way, a general static library is made;

106. Please write an XML file to describe a bookshelf. There are two books on the shelf. The categories of books are cooking and children. The title and author are required to be included in the tag. The category should be represented by attribute


Title 1 < title > 1

Author 1 < author > 1


Title 2 < title > 2

Author 2 < author > 2


107. What is the biggest difference between strcpy and memcpy?

Answer: 1. The content of the copy is different. Strcpy can only copy strings, while memcpy can copy any content, such as character array, integer, structure, class, etc.

2. The method of copying is different. Strcpy does not need to specify the length. It ends when it encounters the string terminator “0” of the copied character, so it is prone to overflow. Memcpy is based on the

Three parameters determine the length of the copy.

3. Different uses. Strcpy is usually used when copying strings, and memcpy is generally used when copying other types of data

108. G + +, what is LD? Declare compilation options – dsupport_ BLUETOOTH =

What’s the use of 1?

A: G + + is GNU’s C + + compiler;

109. @ class usage

answer :@class It is only used to declare the instance variable of a class in the header file

110. Delegate uses assign or retain to briefly explain the reason

A: assign to prevent circular references;

111. What should I pay special attention to in the conversion process between nsstring and nsdata?

Solution: convert nsstring to nsdata object

NSData* xmlData = [@”testdata”dataUsingEncoding:NSUTF8StringEncoding];

Convert nsdata to nsstring object

NSData * data;

NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

Convert nsdata to char*

NSData *data;

char *test=[data bytes];

Char * to nsdata object

byte tempData = malloc(sizeof(byte)16);

NSData *content=[NSData dataWithBytes:tempData length:16];

Attention should be paid to the encoding format of nsdata in the process of conversion


Set the breakpoint first, and then pop out the nsdata variable on the console to see what will be displayed.

If the nsdata in the Po is readable and the content of the text can be seen directly, the [nsstring stringw] is used ithFormat:NSData ](the nsdata here refers to the nsdata variable that you need to convert to nsstring).

If the nsdata in the Po is unreadable and garbled, it usually has encoding format. The most commonly used one is nsutf8stringencoding, and the other is nsasciistring encoding. You can find the enumeration type of encoding format in Apple documents and try them one by one.

112. Please use code to determine whether an object obj supports a method

Solution: if ([ srespondsToSelector:@selector (print:)]) {

[s print: @ “support this method”];


113. Please use simple code to show the definition and implementation of @ protocol

Step 1: declare the protocol

@protocol MarryMe



Step 2: agent declaration

@property(nonatomic,assign)id myDeleget;

. m file

The third step of warning agent: agent execution protocol method

[self.myDeleget makeMoney];

Agent. M file

Step 4 of warning agent: sign the agreement

@interface Boy : NSObject

Girl *girl = [[Girl alloc] init];

Step 5: becoming an agent

girl.myDeleget = self;

[girl getMessage:message];

Step 6 of warning protocol proxy: implement protocol method




/ It’s not about IOS_ /114. Please describe the function of homepage in InDesign

115. Please describe your future career plan for the job

Solution: the answer is not unique, if necessary, please plan to live Baidu

There is one 116.3 liter cup and one 5-liter cup. The shape of the cup is irregular. Ask how to get 4 liters of water. There is unlimited water. (please write down the reasoning process)

Solution: first fill the 5-liter glass, and then pour the water in the 5-liter cup into the 3-liter cup. After the 5-liter cup is filled, the remaining 2-liter water in the 5-liter cup is poured into the 3-liter cup, and then the 5-liter cup is filled. Then fill the 3-liter cup with the water from the 5-liter cup, and then the 5-liter cup will have 4-liter water left in the 5-liter cup

117. What are the data persistence storage schemes?

Solution: the so-called persistence is to save the data to the hard disk, so that after the application or machine restart, it can continue to access the previously saved data. In IOS development, there are five schemes for data persistence

Plist file (attribute list)


Nskeyedarchiver (archive)

SQLite 3


118. What methods of network communication have been used?

Solution: there are two types of network communication methods for IOS devices

1. Use socket to communicate.

2. Use asynsocket class library for communication.

119. How to handle multiple network requests concurrency?

Solution: / / understand (concurrency) when there are multiple threads operating, if the system has only one CPU, it is impossible to run more than one thread at the same time. It can only divide the CPU running time into several time periods, and then allocate the time periods to each thread for execution. When the thread code of a time period is running, other threads are suspended. This method is called concurrent.

In this case, it is recommended to use a third-party network library. For example, AF networking. Concurrency can also be controlled through GCD and nsoperation queue

120. Briefly introduce KVC and KVO. What scenarios can they be applied to?

Solution: KVO: key value monitoring, observe a certain attribute method

KVC: key value encoding, which is an indirect access to the properties of an object

121. Let’s talk about the concept of runtime, message

Send what happens if I can’t find a response object?

Objc runtime is actually a runtime library, which is basically written in C and assembly. This library makes C language have the ability of object-oriented.

  1. Can IOS be embedded in other languages? How to implement it?


  1. What is the final file generated by IOS mobile development and what is its structure?

Finally, the package is completed with an. IPA file, which can be installed on qualified mobile phones through iTunes and other tools

  1. How to use the push / Pop function in UINavigationController

1. Use pushviewc when using UINavigationController ontroller:animated

—-Return to previous view [[selfnavigationcontroller] popviewcontrol rAnimated:YES ];

—PS: push will automatically add a back button in the left bar of navigation, and its response method is to return. So you don’t need to write the return method, just click the back button.

2. Use presentmodal viewc in other times ontroller:animated

[selfpresentModalViewC ontroller:controller animated : Yes]; / / Yes has animation effect

—–Return to previous view [selfdismissmodalviewcontrol] rAnimated:YES ];

3. Generally, addsubview is not used to switch views

UINavigationController is the navigation controller. If pushviewcontroller is used, it will jump to the next viewcontroller, and click return to return to the current viewcontroller;

If it’s addsubview, it’s still the operation of the current viewcontroller. It’s just that a layer of view is “covered” on the top of the current view. In fact, the original screen is at the bottom, so it can’t be seen.

  1. How does uiview need to redraw the whole interface and what methods need to be called?

Uiview setneedsdisplay and setneedslayout methods. First, both methods are executed asynchronously. Setneedsdisplay will call the drawRect method automatically, so that you can get uigraphicsgetcurrentcontext and draw. Setneedslayout calls layoutsubviews by default, which can process some data in the subviews.

To sum up, setneedsdisplay is convenient for drawing, and layoutsubviews is convenient for data

Setneeddisplay tells the view that it has changed and needs to redraw itself

  1. What is the structure of plist file?

Plist files are usually used to store user settings, and can also be used to store bundled information, which was provided by resource branches in older Mac OS.

Plist is mainly composed of core function types. These types can also be put into nsdictionary and nsarray to generate more complex data types

  1. What are the binary data types in IOS and how are they converted to nsstring?

Nsdata: the data type used to store the binary

The nsdata class provides a simple way to set up a buffer, read the contents of a file into a buffer, or write the contents of a buffer to a file.

Invariant buffer (nsdata class), can also define variable buffer (nsmutabledata class).

Nsdata and nsstring transfer to each other:

NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];

//Convert nsstring to nsdata type

NSString * newStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

  1. Is there a GBK character encoding description in IOS? That is, nsutf8stringencoding. If so, what is it like?


  1. How are gestures implemented in IOS?

130. Talk about the design patterns you know, what you have used, and their shortcomings

1. MVC: advantages:

1. Developers can focus on only one layer of the whole structure;

2. It is easy to replace the original level with a new implementation;

3. It can reduce the dependency between layers;

4. It is conducive to standardization;

5. It is conducive to the reuse of each layer of logic.


1. The performance of the system is reduced. This is self-evident. Without the hierarchical structure, many businesses can directly visit the database to obtain the corresponding data, but now it has to be completed through the middle layer.

2. Sometimes it leads to cascading modifications. This kind of modification is especially reflected in the top-down direction. If a function needs to be added in the presentation layer, it may be necessary to add corresponding code in the corresponding business logic layer and data access layer to ensure that the design conforms to the hierarchical structure.

2. Advantages of observer model

1. The observer pattern establishes an abstract coupling between the observed and the observed. All the observant role knows is a list of concrete observers, each of which conforms to an abstract observer interface. The observed does not know any specific observer, it only knows that they all have a common interface.

Since the observant and the observer are not tightly coupled, they can belong to different levels of abstraction. If the observer and the observer are thrown together, the object must cross the level of abstraction and concretion.

2. Observer mode supports broadcast communication. The observer will send a notice to all registered observers,

Disadvantages of the observer model:

1. If an observed object has many direct and indirect observers, it will take a lot of time to inform all the observers.

2. If there is a cyclic dependency between the observed, the observed will trigger a circular call between them, leading to the system crash. Pay special attention to this when using the observer mode.

3. If the notification to the observer is delivered asynchronously through another thread, the system must ensure that the delivery is in a self-adaptive manner.

4. Although the observer model can make the observer know that the observed object has changed at any time, the observer mode has no corresponding mechanism to make the observer know how the observed object changes.

3. Single case mode: main advantages:

1. Provides controlled access to a unique instance.

2. Because there is only one object in the system memory, system resources can be saved. For some objects that need to be created and destroyed frequently, singleton pattern can undoubtedly improve the performance of the system.

3. Allow variable instances.

3. Singleton mode: main disadvantages:

1. Because there is no abstract layer in the simple profit model, it is difficult to extend the singleton class.

2. To some extent, it violates the “single responsibility principle”.

3. Abusing singleton will bring some negative problems. For example, in order to save resources, the database connection pool object is designed as a singleton class, which may lead to connection pool overflow due to too many programs sharing connection pool objects. If the instantiated object is not used for a long time, the system will consider it as garbage and be recycled, which will lead to the loss of object state

131. What are the data persistence storage schemes?


(attached website:

There are basically four ways of data persistence in IOS: attribute list, object archiving, SQLite3 and core data

1. Attribute list (nsuserdefaults, used to store configuration information)

The main class involved: nsuserdefaults. Generally, [nsuserdefaults standarduserdefaults] is enough

2. Object archiving

In order to use object archiving, objects must implement nscoding protocol. Most Object C objects conform to nscoding protocol, and can also implement nscoding protocol in user-defined objects. To implement nscoding protocol, implement two methods


SQLite’s database permissions only depend on the file system, and there is no concept of a user account. SQLite has database level locking and no network server. It needs memory, other overhead is very small, suitable for embedded devices. All you need to do is compile it correctly into your program.

4.Core Data

Core data essentially uses SQLite to save data, but it doesn’t need to write any SQL statements.

To use core data, you need to design entities and define their properties and relationships in the data model editor in Xcode. After that, the data persistence is completed by manipulating these objects and combining with core data

132. What methods have been used for network communication?

(attached website:

It’s also code interpretation

The network communication methods of IOS devices can be divided into two categories as follows:

1. Use socket to communicate.

Taking advantage of TCP, for TCP, it is necessary to distinguish between the server and the client. Server: the usual method is to monitor whether there is a client connection after the server is started. If there is a connection, establish communication with the client. The client usually connects to the server. After the connection is successful, it wants to send data.

2. Use asynsocket class library for communication.

133. How to handle multiple network requests concurrency?


(attached website:

You can read the code carefully

1. Concurrency when there are multiple threads operating, if the system has only one CPU, it is impossible for it to run more than one thread at the same time. It can only divide the CPU running time into several time periods, and then allocate the time periods to each thread for execution. When the thread code of a time period is running, other threads are in the suspended state. This method is called concurrent.

2. Parallel operation when the system has more than one CPU, the thread operation may not be concurrent. When a CPU executes a thread, the other CPU can execute another thread. The two threads do not preempt each other’s CPU resources and can be carried out simultaneously. This method is called parallel.

3. Distinguishing concurrency and parallelism are two concepts that are similar and different. Parallelism means that two or more events occur at the same time, while concurrency refers to the occurrence of two or more events at the same time interval.

134. Briefly introduce KVC and KVO. What scenarios can they be applied to?


(attached website:

KVC:NSKeyValueCoding It is a mechanism that can access class properties directly through the name of the string (key), rather than through the calling setter and getter methods.

The operation method of KVC is provided by nskeyvaluecoding protocol, and nsobject implements this protocol. In other words, if the object is a sub object of nsobject, KVC operation is supported. KVC has two operation methods, one is setting value, the other is value, which can be understood as getter and setter. However, there are two methods to set object value, setValue: property value fo RKey: property name (general setting, for example, setting nsstring, nsnumber and other basic class types; setetvalue: property value; forkeypath: Property path

Two KVO:NSKeyValueObserving A mechanism that allows an object to receive notification when its properties are modified. Every time the attributes of the specified observed object are modified, KVO will automatically notify the corresponding observer, which is equivalent to the observer pattern in the design pattern.

Key value observing (KVO) is based on KVC and can observe the KVC key of an object For the change of path value, the next example is implemented in viewdidload of IOS view, which is similar to KVC, but it can monitor the change of value. It is very simple to implement. Addobserver adds observation, observavevalueforkeypath observes the events after the change. Finally, the following listening events need to be destroyed,

135. What are the methods to implement multithreading and what are the differences?






Thread is relatively lightweight among the three paradigms, but it is also the most responsible one to use. You need to manage the life cycle of the thread and the synchronization between threads. Threads share part of the memory space of the same application, and they have the same access to data. In general, you have to lock the same thread before accessing the same data. In IOS, we can use a variety of forms of thread:

Cocoa threads: use nsthread or directly from the class method performselectorinb of nsobject ackground:withObject : to create a thread. If you choose thread to implement multithreading, nsthread is the official preferred method.

Cocoa operations is implemented based on Objective-C. the class nsoperation encapsulates the operations that users need to perform in an object-oriented manner. We only need to focus on what we need to do, and we don’t have to worry too much about thread management and synchronization, because nsoperation has encapsulated these things for us. Nsoperation is an abstract base class, and we must use its subclasses. IOS provides two default implementations: nsinvocationoperation and nsblockoperation.

Grand central dispatch (GCD): iOS4 has just started to support. It provides some new features, as well as the runtime to support multi-core parallel programming. Its focus is higher: how to improve efficiency on multiple CPUs.

136.The ios/osx’s graphics is bassed onOpenGL . what is OpenGL?

IOS / OS X graphics are based on OpenGL. What is OpenGL?

(attached website:

Official explanation: OpenGL is hardware based graphics acceleration in OS X power core animation, core images, and quartz extremes and gives your app access to amazing 3D graphics processing power. Create a range of applications using industry standard graphics APIs, including games, animation software, and medical imaging solutions.

Baidu’s explanation:

OpenGL: (Open Graphics Library) is a professional graphic program interface that defines a cross programming language and cross platform programming interface specification. It is a powerful and easy to use bottom graphics library for 3D images (2D images are also available). Computer 3D graphics refers to the technology of converting the 3D space described by data into 2D images and displaying or printing them. OpenGL is the program library supporting this transformation. It originated from iris GL developed by SGI company for its graphics workstation, and developed into OpenGL in the process of cross platform porting. OpenGL is designed to be independent of hardware and window system. It can be used on computers of various operating systems. It can work in client / Server Mode under network environment. It is a standard graphics library for high-end applications such as professional graphics processing and scientific computing