Answers to some questions about IOS interview
April 26, 2015
This post is primarily an answer to a list of questions about the iOS programmer, as well as sorting out the knowledge that you already have.
If you have questions about the answer in this post, you can leave a comment below. If there is a problem, I will definitely modify the:-)
Question and Answer 1. What is ARC? (What ARC was born to solve the problem?)
ARC is the abbreviation for Automatic Reference counting, which is the automatic reference count. This is the memory management mechanism introduced by Apple in IOS5. Objective-c and Swift use ARC to track and manage the memory usage of the app. This mechanism allows developers to eliminate the need to type retain
and release
, not only to reduce the risk of program crashes and memory leaks, but also to reduce the developer's workload and greatly improve the flow and predictability of the program. But ARC does not apply to Core F Oundation framework, you still need to manage your memory manually.
2. What is the difference between the following keywords:
assign vs weak
,
__block vs __weak
assign
And weak
is used to specify the semantics of memory management for a property when declaring a property.
assign
Used for simple assignment, does not change the reference count of the attribute, used in Objective-c NSInteger
, and in the CGFloat
C language, and int
float
double
so on data types.
weak
For an object type, because weak
it does not change the reference count of the object and does not hold an object instance, when the object is discarded, the weak reference is automatically invalidated and assigned to nil
, so it can be used to avoid the problem that a circular reference from two strong references causes memory to fail to release.
__block
And __weak
between is really great, but they are used to modify variables.
- The former is used to indicate that the currently declared variable can change the value of a variable in a block after it has been captured by the block. Because the block declaration also intercepts the values of all the automatic variables used by the block, these values only have "use rights" in the block and do not have the "right to modify". The specifier, however,
__block
provides the block with the right to modify the variable.
- The latter is the ownership modifier , what is the ownership modifier? Here's another issue, because when ARC is valid, the ID type and object type are different from the other types in C, and you must attach the ownership modifier. There are 4 types of ownership modifiers:
- __strong
- __weak
- __unsafe_unretained
- __autorelease
__weak
weak
The only difference is that the former is used for the declaration of a variable, while the latter is used for the declaration of a property.
3.
__block
Does the meaning of arc and non-arc mean the same?
__block
variables captured under ARC are retain by the block, which may cause circular references, so a weak reference must be used to resolve the problem. Under non-ARC, the variable can be modified directly using the __block
specifier, because the block does not retain the captured variable under non-arc.
4. Use
nonatomic
Must be thread-safe?
nonatomic
The memory management semantics are non-atomic , non-atomic operations are inherently thread insecure, and atomic
the operation is atomic, but does not mean that it is thread-safe , it will increase the correct probability, can better avoid threading errors, However, it is still thread insecure.
When used nonatomic
, the setter and getter operations of a property are non-atomic, so when multiple threads read and write to a property at the same time, the final result of the property is unpredictable.
When used atomic
, although the read and write of attributes are atomic, a thread error can still occur: when thread A writes, the read or write operations of other threads wait for the operation to occur. When a thread writes, the B thread writes, and then when the a thread reads, It gets the value in the B thread, which destroys thread safety and causes the program to crash if it is release before a thread-read operation. So just using it atomic
doesn't make thread safe, and we also need to add threads to lock
ensure thread security.
atomic
are not necessarily thread-safe, nonatomic
even more needless to say.
5.describe a retain cycle example that you have encountered. 6.
+ (void)load;
And
+ (void)initialize;
What's the use?
When a class object is introduced into a project, runtime sends a message to each class object load
. The load
method is also very magical, because it is called only once for each class or even the classification is introduced, the order of the call is that the parent class takes precedence over the subclass, and the subclass takes precedence over the classification. and method is not automatically inherited by the class, and the methods in each class load
do not need to viewDidLoad
invoke the method of the parent class like a method. Because the load
method is import
called once when the class is invoked, this is often the best time to change the behavior of the class. I'm dknightversion. Used method swizlling
to modify the original method, it is implemented in the classification load
.
initialize
There are load
some differences between methods and methods, and although they are called once throughout the runtime, they are called before the first method of the class executes , that is, initialize
the call is lazy , Its implementation is basically the same as the lazy initialization properties we use in our usual way. I have not encountered the need to use this method in the actual project, in which the static variable is primarily set and used to ensure that certain conditions must be met before the instance is initialized .
7. Why a function call is called in other languages, Objective-c is sending a message to the object (talk about the runtime's understanding)
We say in other languages like: C, Python, Java, C + +, Haskell ... Refers to a function call or method call (object-oriented). A function call is determined at compile time which function (method) will be called, and the compiler will be able to check the correctness of the function execution at compile time.
However, Objective-c (OBJC) is a dynamic language, and the entire OBJC language is determined to postpone all work to the runtime as much as possible. It is based on the runtime to work, runtime is the soul of OBJC, its core is the message sent objc_msgSend
.
What makes Objective-c truly powerful was its runtime.
All messages will be determined at run time and will be [obj message]
converted to execute at run time objc_msgSend(id self, SEL cmd, ...)
, which will look for the corresponding selector from the Select child table and bind the selector to the implementation at runtime. If the corresponding implementation is not found, a message forwarding process like Black magic will be entered. . Call the + (BOOL)resolveInstanceMethod:(SEL)aSelector
method, in which we can dynamically generate the method for the class .
We can almost use runtime magic to change everything in objective-c: and class
property
object
ivar
method
protocol
Here's the main application:
- Introspection
- Add attributes dynamically for classification
- Using the method to modify the original method implementation
- ...
8. What is Method swizzling?
method swizzling
is actually a technique that dynamically modifies the implementation of the original method at run time, which is actually based on the characteristics of the OBJC runtime, and method swizzling
the core approach is method_exchangeImplementations(SEL origin, SEL swizzle)
. Using this method, you can dynamically change the original method implementation at runtime, in Dknigtversion (for IO S application to add night mode) can see a lot method swizzling
of use, the method of call time is in the load
method mentioned above, initialize
do not change the method in the method to achieve the reason is that the initialize
quilt class can inherit and re-execute eventually lead to infinite recursion , and load
and will not be inherited.
9.
UIView
And
CALayer
What's the matter?
See this question can not help but think of freshman in NetEase interview experience, then the two interviewer asked me such a question, UIView
and CALayer
What is the relationship, why so design? I've forgotten what I said at the time. Vaguely remember saying that each one UIView
would correspond to a as to why, then I was too weak to answer.
Behind each one UIView
corresponds to one of the Core Animation
frames CALayer
. Each is a CALayer
UIView
proxy.
Many of the methods you in UIView simply delegate to the layer
In IOS, when you're dealing with one another, you're UIView
actually working on it CALayer
. Although sometimes you do not know (direct operation does CALayer
not have a significant increase in efficiency).
UIView
is actually the right CALayer
lightweight package. UIView
inherited from UIResponder
, used to handle events from the user; it inherits from the CALayer
NSObject
rendering and animation that is primarily used to process layers. There are several reasons for this design:
- You can
UIView
handle events such as interacting with users, touching, clicking, dragging, and so on at a higher level, and these are all done at UIKit
this level.
UIView
and NSView(AppKit)
the implementation is extremely different, and the use Core Animation
can be used to implement the underlying code reuse, both on the MAC and the IOS platform are using nearly the same Core Animation
code, so we can be abstracted on this level on both platforms UIKit
and AppKit
for different framework of the platform.
CALayer
The only reason for this is that it is easy to migrate to different platforms, and if you are only using Core Animation
tiers to develop, you need to write more code to handle the user's interaction time.
10. How to provide high-performance
UIImageView
Add a fillet? (Don't say
layer.cornerRadius
!)
In general, adding rounded corners to Uiimageview or UIKit controls is a matter of change clipsToBounds
layer.cornerRadius
, so that approximately two lines of code can solve the problem. However, using this method will force the Core Animation to render the screen off-screen in advance. , and off-screen drawing can have a negative impact on performance.
We can also use a more complex way to add rounded corners to a picture, where Bezier curves are used.
Uiimageview*imageview=[[Uiimageview Alloc] initWithFrame:CGRectMake(0,0,100,100)]; ImageView. Center=Cgpointmake(200,300); UIImage*anotherimage=[UIImage imagenamed:@ "Image"];Uigraphicsbeginimagecontextwithoptions(ImageView. Bounds. Size, NO,1.0);[[Uibezierpath Bezierpathwithroundedrect: ImageView. Bounds Cornerradius:50] Addclip];[anotherimage drawinrect:imageview.bounds];imageview.image = Uigraphicsgetimagefromcurrentimagecontext (uigraphicsendimagecontext ([self:imageview]
Here the Bezier curves are used to "cut" the picture and give UIImageView
the rounded corners added.
11. Use
drawRect:
What's the impact?
This question is a bit difficult for me to answer, I remember I used this method to draw graphics in my first IOS project Sportjoin, but I've forgotten what I did.
The main function of this method is to draw the image according to the incoming rect
to see the document. The default implementation of this method does nothing, and we can use it in this method Core Graphics
and UIKit
to draw the contents of the view.
The invocation mechanism of this method is also very special. When you invoke the setNeedsDisplay
method, UIKit will mark the current layer as dirty, but it will still show the original content until the next view render cycle, and the Core Graphics context will be re-established for the layer labeled dirty, and then the in-memory Data to be recovered and then drawn using Cgcontextref.
What is the logic of loading images to Uiimageview in ASIHTTPRequest or sdwebimage?
I have read the source code of Sdwebimage, here on how to give Uiimageview load a picture to do a summary, sdwebimage for UIView provides a classification called Webcache, this category has a most commonly used interface, sd_setImageWithURL:placeholderImage:
which Classification also provides a number of similar methods, which eventually invoke a simultaneous option
progressBlock
completionBlock
method, and in this class the method that is finally called will first check if the corresponding parameters are passed and placeholderImage
set placeholderImage
.
Then get the SDWebImageManager
Singleton call in the downloadImageWithURL:...
method to get the picture, and this manager to get the picture of the process is broadly divided into two parts, it first in the SDWebImageCache
search for the image has a corresponding cache, it will be a URL as the index of the data first in memory to find whether there is a corresponding Cache, if the cache misses, will continue to query the corresponding data on the disk using the MD5 processed key, and if found, will back up the cache in the disk into memory.
However, assuming that we do not have a hit in memory and in the disk cache, the manager invokes a method of the object it holds SDWebImageDownloader
downloadImageWithURL:...
to download the image, which invokes another method during the execution to addProgressCallback:andCompletedBlock:fotURL:createCallback:
store the download and the completed callback when the callback block is the first Times, the method instantiates one and adds the latter to the NSMutableURLRequest
SDWebImageDownloaderOperation
asynchronous download of the downloader-held download queue to begin the picture.
After the picture is downloaded, the image is set in the main thread to complete the asynchronous download and configuration.
13. Design a simple picture memory buffer (including removal policy)
After I read the path of open source Fastimagecache source code to answer.
14.tell me about your experience using instrument to optimize your animation performance. 15.
loadView
What is the role?
This method loads or creates a view and assigns it to the property view
.
loadView
is an UIViewController
instance method, we should never call this method directly [self loadView]
. This is clearly spelled out in Apple's official documentation. It is loadView
view
nil
called when the View controller is acquired but is obtained.
loadView
The specific implementation will do one of the following two things:
If your view controller is associated with a storyboard, it loads the view in storyboard.
If you try to have a controller with no associated storyboard, an empty view is created and assigned to the view
property
If you need to overwrite the loadView
method:
- You need to create a root view.
- Creates and initializes
view
a child view that calls addSubview:
methods to add them to the parent view.
- If you use automatic layout, provide enough constraints to guarantee the position of the view.
- Assigns the root view to the
view
property.
Never call in this method [super loadView]
.
16.
viewWillLayoutSubviews
What is the role?
viewWillLayoutSubviews
The view adjusts the position of the sub-view when the bounds of the view changes, and we can override this method in the view controller to make a change before the view places the child view, which is called when the orientation of the screen changes.
What kinds of Queue are there in GCD? What is the threading model behind it?
The type of queue in GCD depends on how we classify it, and if it is classified according to the number of operands processed at the same time, the queue in GCD is divided into two categories
- Serial Dispatch Queue
- Concurrent Dispatch Queue
A class is a serial dispatch queue, which uses only one thread, waits for the end of the currently executing operation before performing the next operation, which is processed in the order in which it is appended. The other is the parallel dispatch queue, which uses multiple threads at the same time, and if the current number of threads is sufficient, it does not wait for the operation to be performed, and multiple threads are used to perform multiple processing at the same time.
Another way to classify this is as follows:
- Main Dispatch Queue
- Global Dispatch Queue
- Custom Dispatch Queue
The main thread has only one, it is a serial process. All processing that is appended to the Main Dispatch Queue will be executed at Runloop. The Global Dispatch queue is a parallel dispatch queue that all applications can use, and it has 4 execution priorities, Default, low, and Background. Of course we can also use the dispatch_queue_create
create dispatch queue.
is Core Data or SQLite read/write sub-threaded? How does deadlock work?
Core data and SQLite these two I really did not use, I only in the small toy application used Core Data, but found that the goods is too difficult to use, I decisively gave up, SQLite I also used, every time I input SQL statement when I want to spit groove, write some simple also Well, the complex is directly Orz. So I typically use LevelDB for persistent storage of data.
Database read operations are generally multi-threaded, when the data read, we want to ensure that the current state will not be modified, so lock, to prevent the problem due to thread competition. The most important rule for using parallelism in Core Data is that each NSManagedObjectContext
must be accessed only from the process in which it was created .
What is the difference between POST and GET for HTTP?
The request for a get type is idempotent according to the HTTP protocol, while the POST request has side effects, that is, get is used to get some resources, and post is used to change some resources, which may create new resources or update existing resources.
A POST request is more secure than a GET request because you do not add information to the query string on the URL. So it's not a good idea to use GET to collect passwords or some sensitive information.
Finally, the POST request can also transmit more information than a GET request.
20. What is the Binary search tree, and what is its time complexity?
Binary search tree is a two-fork tree to organize, its search for the complexity of the timeO(h) is proportional to the height of the tree and the worst run time is Θ(LGn).
Answers to IOS interview questions