# IOS interview questions of large and small companies in Beijing, Shanghai, Guangzhou, Shenzhen and Hangzhou (with electronic answers)

Time：2021-12-31
##### Interview voice

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

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

Collected and sorted out some IOS related questions, most of which are used by large and small factories for interviews or interviews with others. They can hit most of the interviews and daily work. I hope you can use it to test yourself

Because there are too many answers, I made a PDF document. Because the simple book can’t upload files, I can add my answers if I need answersIOS communication group761407670. The password ‘000’ can be used to obtain documents. Recruiters are also welcome to find jobs and provide a larger platform

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

{

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 location

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

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++) {

printf(“%dn”,array[i]);}

3. Please write a function to calculate factorial

{intt=1,j;

for(j=1;j<=i;j++)

t=t*j;

return t;

}

4. Cocoa touch provides several cores

Animation transition class?

A: cocoa touch provides four cores

Animation transition types: cross fade, push, display and overlay.

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

A: data persistence is essentially writing files, but it is logically divided into many types, such as writing sandboxes, saving on the network, and writing to databases.

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

 changes in database fields or tables after app upgrade will lead to crash. Version management and data migration of coredata become very useful. It is still troublesome to write SQL statements manually.

 coredata can not only manipulate SQLite, but also combine well with icloud. If there are requirements in this regard, coredata will be given priority.

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

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

Answer: Object-C classes cannot be inherited multiple times; Multiple interfaces can be implemented, and multiple inheritance of C + + can be completed by implementing multiple interfaces; Category is a category. Generally, the method of using category to rewrite a class is only valid for this category and will not affect the relationship between other classes and the original class.

7. What is the difference between #import and #include, @ class# What is the difference between import < > and #import “?

Answer: #import is the keyword of Objective-C import header file, #include is the keyword of C / C + + import header file. Using #import header file will automatically import only once and will not import repeatedly, which is equivalent to #include and #pragma [email protected] Class tells the compiler the declaration of a class. When it is executed, it can view the class implementation file, which can solve the mutual inclusion of header files# Import < > is used to contain the system header file, #import “is used to contain the user header file.

8. What are the functions of the attributes readwrite, readonly, assin, retain, copy and nonatomic, and in which case?

Answer: readwrite is a readable and writable feature; When getter and setter methods need to be generated

Readonly is a read-only feature, which 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 incoming parameter to the instance variable; Only when setting variables;

Retain indicates the holding feature. The setter method retains the passed in parameter first and then assigns a value. The retaincount of the passed in parameter will be + 1;

Copy refers to the copy feature, and the setter method copies a copy of the incoming object; When a new variable is required.

Nonatomic nonatomic operation, which determines the setter generated by the compiler

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

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

retain)NSString name; Write a setter method to complete @ 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 types of objects are obj at compile time and runtime?

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

11. Currently programmed function: int

rand100(). The function can return a random integer from 0 to 99 and ensure equal probability Please use this function to implement int rand10000(), and return a random number of 0 ~ 9999 with equal probability (other system functions cannot be used)

12. Tom is going to have a party at home now. Although he has many chopsticks, the length of these chopsticks is not exactly the same. First, the length of each chopstick is known, and each guest is required to get two chopsticks of the same length

, ask for the maximum number of guests you can invite

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

13. There is an integer sequence. You can exchange any two numbers to get a new sequence How many possible results can we get (Note: no matter how 3,3,3,3 are exchanged, only one sequence can be obtained)

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

14. There is an array with M rows and N columns. It is required to print the array by installing reverse diagonal (upper right – > lower left) Programming implementation: intprintmatrix arrmatrix [M]

The printing order of the following example is:

0->1->4->2->5->8->3->6->9->7->10->11

123

4567

8910 11

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

A. Frame is an alias for boundaries

B. Frame is an inherited class of boundaries

C. The frame’s reference system is the parent graph coordinate, and the boundaries’ reference system is its own coordinate

D. The frame’s reference system is its own coordinates, and the boundaries’s reference system is the coordinates of the parent map

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

A. The functions in delegate are implemented in other classes

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

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

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

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

A. When arc is used to manage memory, the retain and dealloc methods of the object will not be called

B. Autorelease pool will release the objects allocated in it when drawing

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

D. Nszone cannot be used in projects that use arc

18. The following block definition is correct (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: (d) from subclass to parent class once

A. UIView-> UIViewController->UIController

B. UIResponder-> UIControl-> UIView

C. UIControl-> UIResponder->UIViewController

D. UIControl-> UIView-> UIResponder

20. The following description of the use of class methods in IOS development is wrong: (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 (self can be used)

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

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

Answer: assign pointer is assigned, and reference counting is not performed. If it is not set to nil after use, a wild pointer may be generated; Once weak is not used, it will never be used, and no wild pointer will be generated!

32. Can Object-C classes inherit multiple classes? Can multiple interfaces be implemented? What is category? Is it better to override the method of a class method by inheritance or classification? Why?

Answer: Object-C classes cannot be inherited multiple times; Multiple interfaces can be implemented, and multiple inheritance of C + + can be completed by implementing multiple interfaces; Category is a category. Generally, the method of using category to rewrite a class is only valid for this category and will not affect the relationship between other classes and the original class.

32. How to use IOS devices for performance testing?

Answer: Profile – > instruments – > time profiler

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

Answer: polymorphism. It mainly delays the determination of data type from compile time to run time. This problem actually involves two concepts, runtime and polymorphism. In short, the runtime mechanism allows us to determine the class of an object and call the specified methods 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. It means that all biological classes (life) use the same method eat; human beings belong to biology and pigs belong to biology. After inheriting life, they implement their own eat, but we only need to call their own eat methods. That is, different objects respond to the same message in their own way Therefore, it can also be said that the runtime mechanism is the basis of polymorphism.

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

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

35. Is reading a file an input stream or an output stream?

36. Briefly describe the relationship between calayer and uiview

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

Conclusion:

Uiview is from calayer, higher than calayer, and is the 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 the instance method first. When you write a method for 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.

On the contrary, a static method does not need to access the member variables of an instance, and it does not need to change the state of an instance. We define this method as a static method.

38. What are the common Object-C data types? What is the difference between and CD basic data types?

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

39. What are the animation effects of uiview

For example, uiviewanimationoptioncurveeaseinout

UIViewAnimationOptionCurveEaseIn

UIViewAnimationOptionCurveEaseOut

UIViewAnimationOptionTransitionFlipFromLeft

UIViewAnimationOptionTransitionFlipFromRight

UIViewAnimationOptionTransitionCurlUp

UIViewAnimationOptionTransitionCurlDown

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

A: I understand

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 into the executable file. If it is used for many times, there will be redundant copies, which is equivalent to the jar package in Java. Compile some classes into a package. If you import this file in different projects, you can use the classes in it,

42. What is a sandbox model? Which 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 the sandbox cannot be copied to other application folders, nor can files in other application folders be copied to the sandbox.

3. Apple prohibits any file from reading or writing outside the sandbox, and applications from writing content to folders outside the sandbox.

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

There are three folders in the root directory of the 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、AppName. App Directory: This is the package directory of the application, including the application itself. Because the application must be signed, you cannot modify the contents of this directory at run time, otherwise the application may not start.

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

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

Caches Directory: used to store application specific support files and save information required during application restart.

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

Several directory acquisition methods 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 cache directory path

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

NSString *cachesDir = [paths objectAtIndex:0];

//Get TMP directory path

NSString *tmpDir = NSTemporaryDirectory();

//Get the path of a picture resource (apple. PNG) in the current package

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

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

example:

NSFileManager* fm=[NSFileManagerdefaultManager];

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

//The following is the path to save the file

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

//Get all file names in a directory

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

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

//Or

}

43. What is the agreement? What does it do?

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. In short, a protocol defines an interface, and other classes are responsible for implementing these interfaces. If your class implements a method of a protocol, it is said that the class follows the protocol.

Role of the agreement:

1. Define a set of public interfaces

@Required: the method that must be implemented

@Optional: optional implementation method (none can be implemented)

2. Value transfer by delegate:

It is a design pattern in itself. It means entrusting others to do something.

For example, when passing values between two classes, class a calls the methods of class B, and class B notifies class a of problems during execution. At this time, we need to use a delegate.

Another example: when the value transfer between the controller and the controller jumps from C1 to C2, and then returns from C2 to C1, you need to notify C1 to update the UI or do other things. At this time, we use the delegate value transfer.

44. How do you perform memory leak detection when developing large projects?

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

After starting this tool, run the project. The memory leak can be displayed in the tool. Double click to find the source code location, which can help deal with the memory leak.

45. Have you implemented a framework or library for others to use? If yes, please talk about your experience in building frameworks or libraries; If not, please imagine and design the public API of the framework, and point out how to do it and what aspects to pay attention to, so that others can easily use your framework

46. App from creating an app to putting it on the shelf (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 iTunes connect website, create an app application, set the corresponding information, upload the app package file, and submit it for approval

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

Fibonacci sequence recurrence formula 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){

return1;

}

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

}

48. Given two ordered arrays a and B, please write a function to find their common elements: 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. Implementation principle of KVO?

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

52. How to assign a value to the private property of an object?

Answer: use KVC (key value code) to assign values to private attributes of objects

53. What is the essence of block? Why change the value of the external variable in the block and add a value to the external variable_ Block modification, plus_ What is the principle of block modification?

A: (1) block is essentially a data type. It is mostly used for parameter passing instead of proxy methods (proxy methods are recommended if there are multiple parameters to be passed or multiple proxy methods to be implemented). It is less used for passing as return values Block is an OC object. Its function is to save code fragments, prepare code in advance, and execute it when needed

(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 does block cause circular reference and how to solve it?

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

When self owns a block, self’s method (or some attribute owned by self) is called in the block. Form you have me and I have you. This kind of time will cause circular reference

When 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 generally be released soon, so the first case is generally considered

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

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

A: (1) when signing its proxy with nsurlsession, there will be a circular reference problem because its proxy is a retain strong reference

(2) Solution

(1) After the download is completed, cancel the nsurlsession session and release the session, with the value of nil.

(2) Perform the same operation when the view is about to disappear. To prevent jumping to the controller before the download is completed.

The details are as follows:

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

• (void)viewWillDisappear:(BOOL)animated

{

[superviewWillDisappear:animated];

//When the task is completed, cancel the nsurlsession

[self.sessioninvalidateAndCancel];

//Release session

self.session =nil;

}

56. How to implement get caching by yourself?

Answer: 1 Request data using get

2. The IOS SDK has been cached. 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) it is easy to cause system crash

(2) Solution: turn on the third serial mode and operate with a class (singleton mode)database

58. If a data in JSON format is submitted to the background server, the background server returns a piece of ordinary text. How to implement it with nsurlconnection / nsurlsession / AFN?

Answer: 1 The steps to send a request using nsurlconnection are simple

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

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

(3) Send an nsurlrequest using nsurlconnection

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

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

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

3) Create session object (nsurlsession)

6) After receiving the response returned by the server, parse the data (XML | JSON | HTTP)

59. Please describe the principle of the internal implementation of sdwebimage

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

1. Memory picture 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 relatively low-level pure C language API. It belongs to a C language library and contains many low-level C language APIs. In the OC code we usually write, when the program runs, it is finally converted into C language code of runtime, and runtime is the behind the scenes worker of OC

(http://www.w2bc.com/article/126999Search in the website: in fact, they are finally converted into C language code of runtime)

（1）GCD：

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

UIImage *image = nil;

dispatch_async(dispatch_get_main_queue(),^{

});

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

UIImage *image = nil;

}

This also applies to communication between child threads.

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

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 and sends an autorelease message, it is added to the automatic release pool at the top of the stack of the current thread. When the automatic release pool is recycled, they are deleted from the stack, and a release operation will be performed on all objects in the pool

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 caching mechanism of the client?

Answer: I can’t describe it briefly. I’ll understand it in detail. It’s enough to pretend to be forcedhttp://www.cnblogs.com/wendingding/p/3950198.html

66. What are the life cycle and related functions of the controller view? How do you use it in development?

1. call viewWillAppear before view display; This function can be called multiple times;

2. After the view is displayed, call viewdidappear;

3. call viewWillDisAppear before the view disappears; The function can be called multiple times (if necessary);

4. before and after the 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 hibernation of threads in runloop, make the threads controlled by nsrunloop work when there is something to do, and make the threads controlled by current runloop hibernate when there is nothing to do

2. Runloop detects the asynchronous time of inputsource (such as clicking, double clicking, etc.) from thread start to thread end, and detects the timesourse synchronization event. When the input source is detected, the processing function will be executed, and a notification will be generated first. Corefunction adds runloop observers to the line to listen for events, which is intended to handle events when they occur.

3. Runloop mode is a collection, including monitoring: event sources, timers, and runloop observers to be notified

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

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

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

Enter the main function in main The uiapplicationmain method is executed in the main function of M, which is the entry point of IOS program!

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

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

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

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

This function will create uiapplication object according to principalclassname, create a delegate object according to delegateclassname, and assign the delegate object to the delegate attribute in uiapplication object

The luiapplication object will send different messages to the delegate object in turn, and then establish the main runloop (event loop) of the application for event processing (first, call the application: didfinishlaunchingwithoptions: of the delegate object)

This function returns only when the program exits normally. If the process is to be forcibly killed by the system, the process will terminate before this function returns

69. How do you use the third-party API?

Cocoa pod import

70. Declare a constant with the preprocessing instruction #define to indicate how many seconds are there in a year? (ignore leap year issues)

Answer: #define second 365_ 24_ 60*60

91. What agents do uitableview need to implement? Lists the functions that must be implemented in the uitableview agent and other commonly used functions

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

How many rows are there in a group

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

The above two methods must be implemented for the implementation of the cell in each line

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

wait…..

92. What do you do when developing an application on IOS?

A: first, There should be a MAC system (buy an apple computer, macbook 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 iPhone / iPod and iPad as test machines, and apply to apple for a developer account every year The annual fee is \$99. Then you can develop your program. After development, publish it to the app store and pass the audit.

*93. For the mixed use of C + + and Objective-C, the following description is wrong ()

//No answer found or C + + java

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

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

C. Mm file mixed with CPP can be used directly

D. The key to CPP using Objective-C is to use interfaces instead of 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 ()

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 choose C!

*96. The following thread management errors are ()

//Uncertain

A. GCD manages a thread pool on the back end

B. Nsoperationqueue is a higher-level encapsulation of nsthread

D. GCD can allocate threads according to different priorities

*97. Data persistence in IOS

A. Attribute list

B. Object archiving

C. SQLite and coredata

D. All above + object archiving

98. The following macro definitions are provided:

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

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

99. The following program is used to return the “blue” string. Please point out the error

//Uncertain

char *GetBlue()

{

char *pcColor;

char*pcNewColor;

pcColor = “blue”;

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

strcpy(pcNewColor, pcColor);

return pcNewColor;

}

A: strcpy is a string copy function, and its function prototype is strcpy (char)dst, ct char *src); Copy a string starting from SRC to the memory starting from DST, and the end flag is’ 0 ‘. Since the length of the copy is not controlled by us, the string copy is easy to make mistakes

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

A: the data types of object are nsstring, nsnumber, nsarray, nsmutablearray, nsdata, etc. These are 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 of the basic data type int or long (the definition of nsinteger is typedef long nsinteger). The difference is that nsinteger determines 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 for short), but GC is not supported in Apple’s mobile terminal, and it is supported in the development of MAC desktop system

Mobile terminal development supports arc (automatic

Arc is a new technology introduced after ios5. Its mechanism is different from that of GC. When writing code, we do not need to send release or autorelease methods to objects, nor can we call the delloc method. The compiler will automatically generate release messages (autorelease) for users at appropriate locations. Arc is characterized by automatic reference technology, which simplifies the difficulty of memory management

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

//Update UI

dispatch_async(dispatch_get_main_queue(), ^{

Nslog (@ “update UI”);

});

});

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

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

104. Briefly describe the implementation of a tableview through storyboard

(key steps for customizing a cell)

A: first, create your own custom cell class, which is called customcell and inherits from uitableviewcell. Define the controls 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 cell style to custom, the cell class to customcell, and the identifier to customcellidentifier. Then, you can add controls in the cell to connect the controls with the controls just defined in customcell.

Finally, add the following code to the tableview: cellforrowatindexpath: proxy method of uitableview of viewcontroller:

[plain]

CustomCell*cell=[tableViewdequeueReusableCellWithIdentifier:@”CustomCellIdentifier”];

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

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

Answer: validarchitectures is set to: armv7 ｜ armv7s ｜ arm64 ｜ i386 ｜ x86_ 64；

The architecture settings remain unchanged (or according to your needs): armv7 ｜ arm64;

Then select IOS device and simulator respectively for compilation, and finally find the relevant A. package and use Lipo – create real machine library A’s path simulator library Path of a – the name of the output composition library a；

This makes a general static library a；

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

Title 1 < title >

Author 1 < author >

<book>

Title 2 < title >

Author 2 < author >

<book>

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

Answer: 1. The copied content is different. Strcpy can only copy strings, while memcpy can copy any content, such as character arrays, integers, structs, classes, etc.

2. Replication methods are different. Strcpy does not need to specify the length. It ends only when it encounters the string terminator “0” of the copied character, so it is easy to overflow. Memcpy is based on its chapter

Three parameters determine the length of the copy.

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

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

What is the effect of 1?

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

109. @ class usage

A: @ class is generally used when declaring the instance variable of a class in the header file It is just a declaration, and the internal implementation is not told to the compiler

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

A: assign to prevent circular references;

111. What should I pay special attention to during the conversion 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];

Convert char * to nsdata object

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

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

Pay attention to the encoding format of nsdata during conversion

resolvent:

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

If the nsdata from Po is readable and you can directly see the text content, you can use [nsstring stringwithformat: nsdata] (here, nsdata refers to the nsdata variable you need to convert to nsstring).

If the nsdata in Po is unreadable random code, it generally has coding format. The most commonly used is nsutf8stringencoding, and nsassiistringencoding. You can find the enumeration type of coding format in Apple documents and try one by one.

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

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

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

}

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

Solution: #warning agent step 1: declare the protocol

@protocol MarryMe

-(void)makeMoney;

@end

## Step 2 of warning agent: declare agent

@property(nonatomic,assign)id myDeleget;

. M file

## Step 3: 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: be an agent

girl.myDeleget = self;

[girl getMessage:message];

## Step 6 of warning protocol proxy: implementing protocol method

-(void)makeMoney{

NSLog(@”aaa”);

}

115. Please describe your future career plan for the position you are applying for

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 cup, then pour the water in the 5-liter cup into the 3-liter cup. After filling the 5-liter cup, there are 2 liters left Then pour out the water in the 3-liter cup, pour the remaining 2 liters of water in the 5-liter cup into the 3-liter cup, and then fill the 5-liter cup Fill the 3-liter cup with water from the 5-liter cup, and there will be 4 liters of water left in the 5-liter cup

117. What are the data persistent storage schemes?

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

Plist file (attribute list)

Preference

Nskeyedarchiver (archive)

SQLite 3

CoreData

118. What methods have been used for network communication?

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

1. Use socket to communicate.

2. Use the asynsocket class library to communicate.

119. How to handle the concurrency of multiple network requests?

Solution: / / understand (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 one time period runs, other threads are suspended This method is called concurrent.

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

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

Solution: KVO: key value listening, method of observing a certain attribute

KVC: key value code, which is an attribute that indirectly accesses an object

121. Describe the concept of runtime, message

What happens if send cannot find a response object?

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

1. Can IOS embed other languages? How?

can’t!!!!!

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

The final package is a IPA files can be installed on qualified mobile phones through iTunes and other tools

1. How does the UINavigationController use the push / Pop function

1. When using UINavigationController, use pushviewcontroller: animated

—PS: after push, the back button will be automatically added in the left bar of navigation, and its response method is to return. Therefore, you generally do not need to write a return method. Just click the back button.

2. Use presentmodal viewcontroller: animated at other times

[selfpresentModalViewController:controller animated:YES];// Yes has animation effect

3. Generally, addsubview is not used to switch views

If it is addsubview, it is still operating on the current viewcontroller, but a layer of view is “covered” on the current view. In fact, the original picture is below and can’t be seen.

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

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

To sum up: setneedsdisplay is convenient for drawing, while layoutsubviews is convenient for displaying data

Setneeddisplay tells the view that it has changed and needs to redraw itself, which is equivalent to refreshing the interface

1. Plist file? What is the structure?

Plist files are usually used to store user settings and can also be used to store bundled information. This function is provided by the resource branch in the old Mac OS.

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

1. What is the binary data type in IOS? How do and nsstring convert to each other?

Nsdata: data type used to store binary

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

Invariant buffers (nsdata class) and variable buffers (nsmutabledata class) can also be defined.

Nsdata and nsstring inter conversion:

NSData * data = [str dataUsingEncoding:NSUTF8StringEncoding];

//Nsstring to nsdata type

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

1. Is there a character encoding description of GBK in IOS? That is, what about nsutf8stringencoding, if any?

can’t

1. How are gestures implemented in IOS?

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

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

2. You can easily replace the original level of implementation with a new implementation;

3. It can reduce the dependence between layers;

4. Conducive to standardization;

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

1. It reduces the performance of the system. This is self-evident. If the hierarchical structure is not adopted, many businesses can directly visit the database to obtain the corresponding data, but now they must be completed through the middle tier.

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

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

Because the observed and the observer are not closely coupled, they can belong to different levels of abstraction. If the observed and the observer are thrown together, the object must cross the abstraction and concretization levels.

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

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

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

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

4. Although the observer mode 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 has changed.

3. Single instance mode: main advantages:

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

3. Variable instances are allowed.

3. Single instance mode: main disadvantages:

1. Since there is no abstraction layer in the simple interest pattern, it is very difficult to extend the singleton class.

2. The responsibility of singleton class is too heavy, which violates the “single responsibility principle” to a certain extent.

3. Abusing singleton will bring some negative problems. For example, in order to save resources, designing database connection pool objects as singleton classes may lead to too many programs sharing connection pool objects and connection pool overflow; 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 persistent storage schemes?

(website attached:http://www.cocoachina.com/industry/20130328/5908.html)

There are basically four data persistence methods in IOS: attribute list, object Archive, 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

To use object archiving, objects must implement the nscoding protocol Most Object C objects comply with the nscoding protocol. You can also implement the nscoding protocol in custom objects. To implement the nscoding protocol, you need to implement two methods

3.SQLite3

SQLite’s database permissions only depend on the file system, and there is no concept of user account. SQLite has database level locking and no network server. It needs a lot of memory and other expenses are very small. It is 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 does not need to write any SQL statements.

To use core data, you need to design various entities and define their attributes and relationships in the data model editor in Xcode. After that, the data persistence is completed by operating these objects in combination with core data:

132. What methods have been used for network communication?

(website attached:http://blog.csdn.net/chang6520/article/details/7967698)

It is also code interpretation

There are two categories of network communication methods for IOS devices:

1. Use socket to communicate.

For the benefit of TCP, it is necessary to distinguish between server and 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, you want to send data.

2. Use the asynsocket class library to communicate.

133. How to handle the concurrency of multiple network requests?

(website attached:http://www.cnblogs.com/yanhuaxuanlan/p/4683557.html)

The answers are all codes. You can open the website and read it carefully

1. Concurrency when there are multiple threads operating, if the system has only one CPU, it is impossible for it to carry out 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 one time period runs, other threads are suspended This method is called concurrent.

2. Parallel line when the system has more than one CPU, the operation of threads may be non concurrent. When one CPU executes one thread, the other CPU can execute another thread. The two threads do not preempt CPU resources and can proceed at the same time. 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; Concurrency means that two or more events occur at the same time interval.

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

(website attached:http://blog.csdn.net/zhaozy55555/article/details/8598374

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

The operation method of KVC is provided by nskeyvaluecoding protocol, which is implemented by nsobject. That is, if the object is a child object of nsobject, KVC operation is supported. KVC has two operation methods, one is setting value, the other is value taking, which can be understood as getter and setter. However, there are two methods of setting object value, SetValue: property value forkey: property name (general setting, for example, setting basic class types such as nsstring and nsnumber, setetvalue: property value forkeypath: Property path

2. KVO: short for nskeyvalueobserving. When the properties of the specified object are modified, the mechanism allows the object to receive notification. Each time the properties of the specified observed object are modified, KVO will automatically notify the corresponding observer, which is equivalent to the observer mode in the design mode.

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

135. What are the methods and differences of multithreading?

2.NSOperationQueue

3.GCD

difference:

Cocoa operations is implemented based on Objective-C. class nsoperation encapsulates the operations that users need to perform in an object-oriented manner. We just need to focus on what we need to do without worrying about thread management, synchronization and other things, 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 only begun to support. It provides some new features and runtime to support multi-core parallel programming. It focuses on 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?

(website attached:https://developer.apple.com/opengl/)

Official explanation: OpenGL is hardware based graphics acceleration in OS X’s power core animation, core image, and quartz extremes and gives your application access to amazing 3D graphics processing capabilities. Use industry standard graphics APIs to create a range of applications, including games, animation software, and medical imaging solutions.

Baidu’s explanation:

OpenGL: (Open Graphics Library) refers to a professional graphic program interface that defines a cross programming language and cross platform programming interface specification. It is used for 3D images (two-dimensional) is a powerful and easy to call bottom graphics library. Computer three-dimensional graphics refers to the technology that converts the three-dimensional space described by data into two-dimensional images through calculation and displays or prints them. OpenGL is the program library that supports this conversion. It originates from iris GL developed by SGI company for its graphics workstation and developed into Is OpenGL. OpenGL is designed to be independent of hardware and window system, available on computers of various operating systems, and can work in client / Server Mode in network environment. It is a standard graphics library in high-end application fields such as professional graphics processing and scientific computing

## Redis featured Q & A

Redis data type type brief introduction characteristic scene String (string) Binary security It can contain any data, such as JPG pictures or serialized objects. One key can store up to 512M It can be used to do the simplest data. It can cache a simple string or a JSON format string. The implementation of redis […]