IOS interview questions

Source: Internet
Author: User
Tags notification center

IOS interview questions
MVC

MVC is an architecture mode. The advantages of this architecture mode are business logic, data, and view separation. High Cohesion and low coupling

From Cocoa Design Patterns:

The main purpose of MVC is to remove the coupling between model subsystems and views so that they can be changed independently.

From design patterns:

MVC separates views and models by establishing a "order/notification" protocol. The view must ensure that its display correctly reflects the model status. Once the data of the model changes, the model will notify the relevant views. When the data of each model changes, the model will notify the relevant views, and each view will be refreshed accordingly. This method allows you to provide multiple view representations for a model, and create a new view for a model without rewriting the model.


M-Model V-View

C-Controller

Between the Controller and Model, the Controller side is a dotted line, indicating that the Controller can directly access the Model; the Model side is a white solid line, indicating that the Controller cannot be accessed directly, but the Model changes. The Controller wants to know, in this case, the observer mode can be used to indirectly notify the Controller.

Between the Controller and View, the Controller side is a dotted line, indicating that the Controller can directly access the View (if there is a Storyboard, you need to access it through Outlet); the View side is a white solid line, indicating that you cannot directly access the Controller. If the View receives user interaction, it can call back the Controller through the Target Selector, Selector, or Action. If the View needs to obtain data from the Controller (number of cells, giving you an indexPath, when the text of the Cell and TextField that you want to display changes, TextField receives a "Return" button), it calls back to the Controller through Delegate or DataSource. Note: A block is missing in this figure!

Between View and Model is a yellow dual-solid line, which indicates that mutual access or indirect callback are prohibited between the two.

Typical cases:
The Controller retrieves data from the Model and displays the data to the View (its subclass can also be used, such as UIButton). The Controller adds a target selector to the button and calls back to the Controller when the button is pressed, the Controller then updates the Model. When the Model changes, the Controller receives the observer message or notification message and updates the View display style.

What is high cohesion and low coupling?
Extended Interview Questions: What design patterns are commonly used in iOS?
Extended Interview Questions: If MVVM occurs in your resume, self-introduction, or conversation, you will be asked about the difference between the two. Some interviewers will answer the question that the Controller layer in the MVC Architecture mode will become increasingly bloated, while MVVM will not. This answer will deduct points, because the MVC Architecture Model will result in a bloated Controller only when the module's responsibilities are unclear, which means that the interviewer's technical capabilities are insufficient. Therefore, the MVVM concept must be used before it can be answered!
Trap: MVC is an architecture mode. Note that it is not a design mode.
Trap: What is the difference between Notification and KVO? Under what circumstances do I use Notification and KVO?

How to use multithreading in iOS

Answer:

NSThread NSOperation
NSOperationQueue NSInvocationOperation NSBlockOperation GCD
Dispatch_async dispatch_sync dispatch_group dispatch_semaphore dispatch_after dispatch_once dispatch_barrier dispatch_source

Additional questions: differences between NSOperation and GCD

Differences between NSOperation and GCD: GCD
Advantages
Relatively simple to use disadvantages
As long as a GCD task is started, GCD tasks cannot be stopped theoretically because they are written in blocks. If the thread control is complicated, the number of blocks will increase, in this case, the code readability will become worse.
Advantages
The cancel method can be sent like NSThread. Internal Processing Based on the cancel status of the current thread can control the concurrent (asynchronous) or serial (synchronous) threads based on the maximum variable sending volume of NSOperationQueue, which is easier to read than GCD.
Because NSOperation depends on NSOperationQueue (task queue), this task queue object requires additional code for management, allocation, and release.

Extended Interview question: Will NSOperation be stopped immediately when the cancel method is sent?
Extended Interview Questions: What is the significance of stopping immediately?

NSOperation is sent with the cancel method. Will it be stopped immediately? If so, what is the significance?

It does not stop immediately. It only sends a message "I want to cancel you" to the NSOperation object. In NSOperation, You need to determine whether you have received the message "canceled" at the right time, perform some scanning operations, and stop yourself.

This mechanism is similar to double-click the Home key, and draw out the App screen and kill the App. However, the App still receives the-(void) applicationWillTerminate message before it is killed, save data

Differences Between auto, register, static, const, and volatile in C Language

Factory Model
Singleton Mode
Observer Mode
Adapter mode (delegate)
Prototype (copy)

Extended Interview Question 1: differences between the factory model and Singleton Model
Extended Interview Question 2: differences between observer mode and adapter Mode
Extended Interview Question 3: Connection Between KVC and KVO
Interview question 4: differences between KVO and nsnotifcenter Center
Interview question 5: How to Implement the singleton Mode
Trap: Some interviewers will answer MVC, KVO, KVC, and Notification. Note that MVC is the architecture mode, KVO and Notification are the implementation methods of the observer mode in iOS, and KVC is the key value observation encoding, it is not a design model. In addition, the design pattern applies to all programming languages. since it applies to all programming languages, can KVO be used in Java?

How to Implement Singleton Mode

Method 1:

+ (instancetype)sharedInstance {
    static id sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedClient = [[self alloc] init];
    });
    return sharedClient;
}

Method 2:

+ (instancetype)sharedInstance {
    static id sharedClient = nil;
    @synchronized (self) {
        sharedClient = [[self alloc] init];
    }
    return sharedClient;
}

Method 3:

+ (instancetype)sharedInstance {
    static id sharedClient = nil;
    if (sharedClient == nil) {
        sharedClient = [[self alloc] init];
    }
    return sharedClient;
}
What is high cohesion and low coupling?

Cohesion is the closeness of elements in a module. High Cohesion is the closeness of elements in a module.

High cohesion refers to a software module that consists of highly correlated Code and is responsible for only one task, that is, a single responsibility principle.

Coupling: a measurement of the degree of interconnection between different modules in a software structure (coupling is also called inter-block connection. A measure of the closeness between modules in the software system structure. The closer the relationship between modules, the stronger the coupling, and the poorer the module independence. The coupling between modules depends on the complexity of Inter-module interfaces, the call methods, and the transmitted information .)

For low coupling, the superficial understanding is: a complete system, between modules, as far as possible to make it independent. That is to say, let each module complete a specific sub-function as independently as possible. The interfaces between modules are as few as possible and as simple as possible. If the relationship between two modules is complex, it is best to consider further module division first. This facilitates modification and combination.

Let's talk about it.
For example, a ViewController is responsible for the delegate and dataSource of UITableView, the delegate of UITextField, the network request, and the network response and Model update .... This design is a manifestation of poor cohesion. The concept of High Cohesion is similar to the single responsibility principle (SRP) in the "Five Principles of object-oriented design" (SOLID), that is, "one class, only one thing"

What is coupling? It is the dependency between modules. For example, in ViewController, you must depend on View, AFNetworking, and Model... This design is a manifestation of high coupling. The concept of low coupling is similar to the dependency inversion principle (DIP) in the "Five Principles of object-oriented design" (SOLID) and the interface isolation principle (SIP.

What is the difference between NSNotificationCenter and KVO?

The two share the same thing: they are both observer models.
Differences between the two: KVO is the key value observation, and nsicationicationcenter is the notification center. In applicable scenarios, KVO must have a key to observe changes in values. Nsicationicationcenter does not need

If you want to observe the content related to the model, use KVO. Otherwise, use nsicationicationcenter

Trap: Some interviewers will answer that Notification is one-to-one and KVO is many-to-many.

What is a thread? What is a process? What are the differences and connections between the two?

A process is a "program in execution". In iOS programming, multi-process design is not supported. For example, in the Mac system, log on to a QQ number, press the shortcut key Command + N, and then you can log on to a QQ number. Then, the QQ application starts two processes. However, it cannot be enabled in iOS.
In a process, there can be multiple threads, but at least one master thread is running all the time. They can use the resources of the process. For example, multiple threads can operate the Model...
In multi-process design, a process crash does not affect other processes.
In multi-threaded design, a thread crash will affect other threads.
If the process crash, all its threads will crash.

Extended Interview Questions: how to design a thread in iOS?
Extended Interview Questions: thread synchronization problems

Which of the following methods are available for iOS persistent storage? NSUserDefault plist archive/unarchive Database
SQLite
FMDB CoreData
MagicalRecord

Extended Interview question: What is the difference between SQLite and CoreData?
Extended Interview question: What is the difference between CoreData and MagicalRecord?
Extended Interview Questions: If FMDB or SQLite is embodied in your resume or project description, you may be asked about SQL statements for multi-table queries.
How to upgrade the table structure of CoreData?
Extended Interview Questions: Have you ever encountered a deadlock while using CoreData? How can this problem be solved?
Extended Interview Questions: What are your experiences with using the database?
Trap: If multi-Table query SQL is involved, the interviewer may not know it. The interviewer will be given the impression that the previous project was too simple, and the interviewer's technical skills will be doubted.

What is the difference between SQLite and CoreData?

CoreData is the encapsulation of SQLite. In CoreData, the code used to operate the database is the code used to operate the object.

Differences between CoreData and MagicalRecord

MagicalRecord is an encapsulation of CoreData, which is easier to use than CoreData. In addition, it considers the deadlock caused by multi-threaded database operations.

What are the experiences of using databases? Have you ever encountered a deadlock? How can this problem be solved?

Do not operate the database too frequently. Generally, when the program starts, all data in the database is read into the Model. When the program is closed, all data in the Model is read, stored in the database. MagicalRecord

What is the difference between multi-thread synchronization and Asynchronization? In iOS, how does one implement multi-thread synchronization?

Multi-thread synchronization is the queuing effect. Similar to the traffic signal lights at the intersection, the car on the back must go straight, but the car on the front is waiting for the left turn signal light. The light on the back must wait until the car on the front leaves. Otherwise, it will continue to wait.
Multithreading and Asynchronization means "concurrent execution ". Mostly used for blocking tasks. For example, if network requests are synchronized, the main thread will be stuck, the page will not be refreshed, and the user interaction will not be responded... If asynchronous mode is used, the main thread continues to process page refreshes and responds to user interaction. The other thread waits for network response.

Multithreading synchronization can be performed in the following ways:
Dispatch_semaphore
Atomic operation OSAtomic
Lock NSLock
Event NSCondition

Extended Interview Questions: What is the difference between nonatomic and atomic in attribute keywords?

Stack and stack differences

The concept of heap and stack should be Baidu by yourself. Generally, no errors will occur. Only the differences between them are described here.
For example, the following code:

- (void)method {
    NSObject *obj1 = [[NSObject alloc] init];
    NSObject *obj2 = [[NSObject alloc] init];
    NSInteger inta = 0;
    NSInteger intb = 0;
}

Heap content:
According to the memory management rules, with alloc, you must have release. However, if this code is not release, it does not really not require release. Rather, ARC automatically goes to release at the end of the function. The objects obj1 and obj2 are stored in the heap zone. The content of the heap zone must be manually allocated (alloc) and released (release) by the programmer)

Stack content:
The compiler automatically allocates and releases data. The inta and intb integer values must have a memory area for storage. This memory does not need to be allocated by programmers or released by programmers.

Does iOS have multiple inheritance? If no, what should I replace it?

Without multi-inheritance, OC can only be a single inheritance. If you want to implement multiple inheritance, you can use protocol instead.
Extended Interview Questions: because it involves multiple inheritance, if your resume contains other programming languages, you may be asked (Many interviewers will mention C ++ and Java in their resumes, at this time, the interview is very likely to ask about multiple concepts such as inheritance, virtual functions, pure virtual functions, and abstract classes)

Dynamic binding, runtime, and compiling

The following code is available:
NSString *str = [[NSData alloc] init];
str = [str stringByAppendingString:@"abc"]
Will compilation be successful? If the compilation passes, what will happen during the running process?

A: compilation is successful, but the compiler reports a warning. During compilation, str is of the NSString type, but during runtime, an NSData object is created and dynamically bound to NSData. Since str is actually an NSData object, the NSData object does not implement the "stringByAppeningString" method, so it will crash.

# What is the difference between import, # include, and @ class? @ Class represents what? If there is no # import keyword, what would you do?

# Import and # include are both import header files, but # import can ensure "only import once" during compilation, but # include cannot. If you do not have the # import keyword, you can only use the # include keyword. You can add the following code to the imported header file:

#ifndef _HEADER_H // _HEADER_H here should be obtained based on the actual header file name
#define _HEADER_H
// actual content
#endif

@ Class is designed to prevent cross-compilation. Generally, it is an excellent design. It will avoid importing two header files to each other, but sometimes it cannot be avoided. If the two header files are imported to each other, the compiler will report an error. For example:

Teacher. h:

#import "Student.h"
@interface Teacher : NSObject
@property (strong, nonatomic) NSMutableArray*students;
@end

Student. h:

#import "Teacher.h"
@interface Student : NSobject
@property (strong, nonatomic) NSMutableArray*teachers;
@end

In this case, the @ class keyword can be used. Replace the # import cut in the header file with the. m file, and add the @ class keyword to the same position in the header file.

In the property keyword, what are the meanings of assign, weak, retain, strong, copy, atomic, nonatomic, readonly, and readwrite?

For the basic C language type, use assign (CGFloat, long, int, short, NSInteger, NSUInteger)

For proxy, use weak (MRC uses assign)

If it is strongly referenced, you need to change a strong to weak;

If the object needs to save a copy and you do not want to modify it, use copy.

For the rest, strong is used (retain is used in MRC)

Atomic operation: thread security. It is equivalent to adding a thread lock to the getter and settger functions.

Nonatomic
Non-atomic operations-non-thread security

Atomic
Atomic operation-thread security

Self. imageView. money = money;

Strong, retain
Strong is used in ARC, and retain is used in MRC.
Automatic Reference count + 1

- (void)setImage:(UIImage *)image {
    if (_image != image) {
        [_image release];
        [image retain];
        _image = image;
    }
}

- (void)dealloc {
    [_image release];
}

Assign

- (void)setUnknown:(Unknown )var {
    _var = var;
}

Weak
In general, it is the same as assign: if the object to be pointed is destroyed, the pointer will point to nil.

Copy

- (void)setString:(NSString *)string {
    if (_string != string) {
        [_string release]
        _string = [string copy];
    }
}

Readonly
The setter method cannot be called when other classes are used.
In your own class, if you want to use it, you can. in the m file, write an anonymous category, and. you can use the same property content (delete the readonly keyword) in the hfile.

Readwrite
Unsafe
Safe

Second attribute Definition

Q: for other classes, attributes are read-only, but for their own classes, they are readable and writable. How can this problem be solved?
A: directly add the code.

Template. h:

@inteface Template : NSObject
@property (strong, nonatomic, readonly) NSObject *prop;
@end`

Template. m:

@interface Template()
@property (strong, nonatomic) NSObject *prop;
@end

@implementation Template
// ...
@end
IOS capture screen

+[UIImage imageFromView:]

Concept of event responder chain

The responder chain represents a series of responder objects. The event is handled by the first responder object. If the first responder is not handled, the event is passed up along the responder chain and handed over to the next responder ). Generally, the first responder is a vision object or its subclass object. When it is touched, the event is handled by it. If it is not processed, the event will be passed to its vision controller object (if any), then its parent view object (if any), and so on, to the top-level view. Next, we will go from top view to window (UIWindow object) to program (UIApplication object ). If the entire process does not respond to this event, the event will be discarded. In general, in the responder chain, as long as the event is processed by the object, the event will stop being transmitted. However, sometimes the view response method can be used to determine whether to continue to pass events based on certain conditions.

Const and pointer
const int *cnp = 0;
int const *ncp = 0;
const * int cpn = 0;
int * const npc = 0;
int const * const ncpc = 0;
const int * const cnpc = 0;

What are the meanings of the above six rows?

What is the difference between category and class extension?

Extension is an anonymous Category, that is, there is no character in the brackets

What is the difference between category and inheritance?

Inheritance extends the original class in subclass mode.
The category is extended based on the original class.

If you want to allow all uiviews and their subclasses to support one method. For example, UIButton, UILabel, and UIImagView all support a method-(void) customMethod. Should classes be used or inherited?

Answer: Category

Can attributes be extended by category?

Theoretically not, but it can be added using the runtime method. The property is a settger method and a getter method. Therefore, you can directly add the attribute declaration in the header file:

ExtensionObject. h:

#import 
  
   @interface NSObject(ExtensionObject)@property (retain, nonatomic) NSObject *extensionProp;@end
#import 
@interface NSObject(ExtensionObject)
@property (retain, nonatomic) NSObject *extensionProp;
@end

However, the setter and getter methods must be associated with a member variable because the class cannot add member variables. Therefore, we can only save the country by curve:

ExtensionObject. m:

  
   static const void *extensionPropKey = &extensionPropKey;@implementation NSObject(CustomAnimate)- (NSObject *)extensionProp {    return objc_getAssociatedObject(self, extensionPropKey);}- (void)setExtensionProp:(NSObject *)extensionProp{    objc_setAssociatedObject(self, extensionPropKey, extensionProp, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}@end
#import "ExtensionObject.h"
#import 

static const void *extensionPropKey = &extensionPropKey;

@implementation NSObject(CustomAnimate)

- (NSObject *)extensionProp {
    return objc_getAssociatedObject(self, extensionPropKey);
}

- (void)setExtensionProp:(NSObject *)extensionProp{
    objc_setAssociatedObject(self, extensionPropKey, extensionProp, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
Write a factory method for the ARC version and the factory method for the MRC version.
// ARC version
+ (instancetype) factory {
     id factory = [[self alloc] init];
     return factory;
}

// MRC version
+ (instancetype) factory {
     id factory = [[self alloc] init];
     return [factory autorelease];
}
What do you think about the basic principle of memory management?

Basic principles: Who uses (alloc, retain, copy) and WHO releases (release, autorelease ).
TIPS: Always Useself.prop_nameMethod. This can avoid the vast majority of memory leaks.

The difference between deep replication and light replication. How do I implement the Code to obtain a copy version of an object?

Shallow copy: only copy the object itself, not copy the attributes in it.
Deep replication: not only copies the object itself, but also copies the property objects held by the object.

The copied class must implement the NSCopying protocol.

There are two classes: Deep copy version and deep copy version.

Student. h:

#import 
  
   @class Score;@interface Student : NSObject@property (strong, nonatomic) NSMutableArray*score;@end

Student. m:

#import "Student.h"
#import "Score.h"

@implementation Student

-(id) copyWithZone: (NSZone *) zone {
     Student * result = [[Student allocWithZone: zone] init];
     result.score = [self.score copy]; // property must be copied
     return result;
}

@end 

Score. h:

  
   @interface Score : NSObject@property (copy, nonatomic) NSString *subjectName;@property (assign, nonatomic) NSInteger score;@end
#import 
@interface Score : NSObject@property (copy, nonatomic) NSString *subjectName;
@property (assign, nonatomic) NSInteger score;
@end

Score. m:

#import "Score.h"
@implementation Score

- (id)copyWithZone:(NSZone *)zone {
    Score *result = [[Score allocWithZone:zone] init];
    result.subjectName = [self.subjectName copy];
    result.score = self.score;
    return result;
}
@end
Light copy version

Student. h:

#import 
  
   @class Score;@interface Student : NSObject@property (strong, nonatomic) NSMutableArray*score;@end

Student. m:

#import "Student.h"
#import "Score.h"

@implementation Student

- (id)copyWithZone:(NSZone *)zone {
    Student *result = [[Student allocWithZone:zone] init];
    result.score = self.score; // different
    return result;
}

@end

Score. h:

  
   @interface Score : NSObject@property (copy, nonatomic) NSString *subjectName;@property (assign, nonatomic) NSInteger score;@end
#import 
@interface Score : NSObject
@property (copy, nonatomic) NSString *subjectName;
@property (assign, nonatomic) NSInteger score;
@end

Score. m:

#import "Score.h"@implementation Score@end
Is there Memory leakage in ARC?

Memory leakage may occur,
1. If the settger and getter Methods automatically generated by property are not used, the member variables are used. Similarly, memory leakage may occur.
2 If the object reuse (UITableViewCell or UICollectionViewCell) is involved, the observer may be added to observe multiple observers at the same time. When the Model is refreshed

Describe the reuse mechanism. What is automatic release pool? @ Synthesize what is the difference between @ dynamic and dynamic binding?

Extended Interview Questions: how do I do dynamic binding in C ++?

What is the difference between block and protocol? Which one do you prefer when using block? Read the following code to illustrate the differences
@interface Template ()
@property (strong, nonatomic) NSObject * prop;
@end

@implementation Template
-(void) method {
     // explain the difference between the two lines
     self.prop = [[NSObject alloc] init];
     _prop = [[NSObject alloc] init];
}
@end 

A:
self.prop = [[NSObject alloc] init];The setter method automatically generated by the compiler is called, and the reference count is considered internally;
While_prop = [[NSObject alloc] init];The setter method automatically generated by the compiler is not called, and the reference count is not considered. Therefore, memory leakage may occur.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.