iOS face questions and answers

Source: Internet
Author: User
Tags gcd network function

1. Can the class of object-c inherit multiple? Can I implement more than one interface? What is category? How do you rewrite a class in a way that inherits or classifies well?
A: The class of object-c is not multiple inheritance; multiple interfaces can be implemented, and multiple inheritance of C + + can be accomplished by implementing several interfaces; Category is the class, the general situation with good classification, with category to rewrite the method of the class, only valid for this category, will not affect the other classes and the original class relationship.

2. What is the difference between #import and # include, @class, #import <> and #import "" What's the difference?
A: #import是Objective-C import header file keyword, #include是C/c++ import header file keyword, using #import header file will automatically import only once, do not repeat the import, equivalent to # include and #pragma once;@ Class tells the compiler the declaration of a class, when executed, only to see the implementation of the class file, you can resolve the header file of each other, #import <> to include the system header file, #import "" to include the user header file.

3. What are the functions of readwrite,readonly,assign,retain,copy,nonatomic, in that case?
(1) ReadWrite is a readable and writable feature; When you need to generate getter and setter methods
(2) readonly is a read-only feature that only generates getter methods, does not generate setter methods, and does not want attributes to change outside of the class
(3) Assign is an assignment attribute, the setter method assigns the passed parameter to the instance variable, and only when the variable is set;
(4) Retain means holding characteristics, setter method will pass in the parameters of the first reservation, and then assign value, the Retaincount of the incoming parameters will be +1;
(5) Copy represents an assignment attribute, and the setter method copies the incoming object in one copy; When a new variable is required.
(6) Nonatomic Non-atomic operation, determines whether the compiler generated setter getter is atomic operation, atomic represents multithreading security, general use Nonatomic

4. Write a setter method to complete @property (nonatomic,retain) nsstring *name, write a setter method for completing @property (nonatomic,copy) NSString * Name
-(void) SetName: (nsstring*) str {
[Str retain];
[Name release];
name = str;
-(void) SetName: (NSString *) str {
ID t = [str copy];
[Name release];
name = t;

5. For statement nsstring*obj = [[NSData alloc] init]; What type of object does obj have at compile time and run time, respectively?
Compile-time is the type of nsstring; runtime is an object of type NSData

6. What is the difference between the data types of common object-c and the basic data types of C? such as: Nsinteger and int
OBJECT-C data types have nsstring,nsnumber,nsarray,nsmutablearray,nsdata and so on, these are class, after creation is the object, and C language basic data type int, just a certain byte of memory space, for storing values; Nsinteger is a basic data type, not a subclass of NSNumber, and certainly not a subclass of NSObject. Nsinteger is the alias of the base data type int or long (Nsinteger's definition typedef long Nsinteger), the difference is that Nsinteger determines whether it is an int or a long based on whether the system is 32-bit or 64-bit.

What is the nature of the object declared by
An Id-declared object has a runtime attribute, which can point to an object of any type of objcetive-c;

8.objective-c How to manage the memory, say your opinion and solve the method?
OBJECTIVE-C memory management has three main ways of Arc (automatic memory count), manual memory count, memory pool.
(1) (Garbage Collection) automatic memory count: This way is similar to Java in the course of your program's execution. Always have an expert in the back to help you clean up the rubbish, you do not have to consider when it began to work, how to work. You just need to understand, I applied for a memory space, when I no longer use so this memory becomes garbage, I completely forget it, anyway, the high man will help me to clean up the rubbish. Unfortunately, the man needs to consume a certain amount of resources, in the carrying device, the resources are tight goods so the iphone does not support this feature. Therefore, "garbage Collection" is not the scope of this introductory guide, the "garbage Collection" internal mechanism interested students can refer to some other information, but to tell the truth "garbage Collection" is not suitable for beginners to study.
Resolution: Created by Alloc–initial, after the reference count of +1, after each retain reference count +1, then in the program to do the corresponding number of release is good.
(2) (Reference counted) manual memory count: That is, after a period of memory is applied, there is a variable to save the memory is used, we temporarily call it a counter, when the counter becomes 0, then the time to release the memory. For example, when a piece of memory in program A is successfully applied, then the counter is changed from 0 to 1 (we call this process alloc), then program B also needs to use this memory, then the counter is changed from 1 to 2 (we call this process retain). Then program a no longer needs this memory, then program a will reduce this counter by 1 (we call this process release), program B also no longer need this memory, then also the counter minus 1 (this process or release). When the system (that is, the foundation) finds this counter to be 0, the memory recycle program is called to reclaim the memory (we call this process the Dealloc). By the way, if there is no foundation, then maintenance counters, free memory and so on, you need to do the work manually.
Workaround: Typically created by static methods of the class, the function name does not appear in the Alloc or Init typeface, such as [NSString string] and [Nsarray Arraywithobject:], after the creation of the reference count +0, after the function is released after the stack, is equivalent to a local variable on a stack. Of course, you can also extend the lifetime of an object by retain.
(3) (Nsautorealeasepool) memory pool: You can control the timing of memory requests and recoveries by creating and freeing memory pools.
Workaround: The autorelease is joined to the system memory pool, the memory pool is nested, and each memory pool needs to have a create release pair, just like the one written in the main function. The use is also very simple, for example [[[[NSString alloc]initialwithformat:@] Hey you! "] Autorelease], a NSString object is added to the most internal system memory pool, and when we release the memory pool, the objects are freed.

9. What is the difference between an atom (atomic) and a non-atomic (non-atomic) attribute?
(1) Atomic provides multithreading security. is to prevent it from being read by another thread when the write is incomplete, resulting in a data error
(2) Non-atomic: In the environment in which the memory is managed, the parsed accessor retains and automatically releases the returned value, and if Nonatomic is specified, the accessor simply returns the value.

10. Look at the program below, what will the first nslog output? What is the Retaincount of str? What's the second and third one? Why?
nsmutablearray* ary = [[Nsmutablearray array] retain];
NSString *str = [nsstring stringwithformat:@ "test"];
NSLog (@ "%@%d", Str,[str Retaincount]);
NSLog (@ "%@%d", Str,[str Retaincount]);
NSLog (@ "%@%d", Str,[str Retaincount]);
Str Retaincount creates +1,retain+1, joins the array automatically +1 3
Retain+1,release-1,release-1 2
Array removes all objects, all objects within the array automatically-1 1

11. What are some of the principles of memory management? Follow the default rules. Those keyword-generated objects
Need to be released manually? How to effectively avoid memory leaks when combined with the property?
Who applies, who releases
Follow the cocoa touch usage principles;
Memory management mainly to avoid "premature release" and "Memory Leak", for "premature release" need to pay attention to the @property setting characteristics, must use the keyword to the attribute, for "memory leak", must apply for the release, be careful.
The object generated by the keyword Alloc or new needs to be released manually;
Set the correct property properties, for retain need to be released in the appropriate place,

12. How do I perform a performance test on my iOS device?
profile-> Instruments->time Profiler

What is the method for creating threads in Object C? What is the method if you execute code in the main thread? What is the method if you want to defer execution of code?
There are three ways to create a thread: Use Nsthread to create, use GCD dispatch, use a subclass nsoperation, and then add it to Nsoperationqueue; Execute code on the main thread. The method is Performselectoronmainthread, if you want to delay the execution of code can be used PerformSelectornThread:withObject:waitUntilDone:

14. Describe how to implement the MVC development model in the iOS SDK
MVC is a model, an attempt to control the development pattern, and for the iOS SDK, all views are view layers, which should be independent of the model layer and controlled by the view control layer. All user data is the model layer and should be independent of the view. All Viewcontroller are control layers, which are responsible for controlling the view and accessing the model data.

15 shallow copy and deep copy the difference?
Answer: Shallow copy: Copies only pointers to objects, not the reference object itself.
Deep copy: Copies the reference object itself.
That means I have an A object, after copying a copy to get A_copy object, for shallow copy, A and a_copy point to the same memory resource, copy is just a pointer, the object itself resources
There is only one copy, so if we do a modification to a_copy, then we find that the object referenced by A is also modified, which violates the idea of copying copies. Deep replication is a good idea, and there's an in-memory
Two copies of the independent object itself.
Using a friend on the Internet, the popular words will be:
Shallow copy is like you and your shadow, you are finished, your shadow is finished
Deep replication is like you and your clones, you're screwed, your clones are alive.

16. What is the difference between inheritance and category in implementation?
Answer: Category can be in the case of not knowing, without changing the original code to add a new method, can only add, can not delete the changes.
And if the category and methods in the original class produce name collisions, the category overrides the original method because the category has a higher priority.
There are 3 main functions of the category:
(1) The implementation of the class is dispersed across several different files or multiple frameworks.
(2) Create a forward reference to the private method.
(3) Add an informal agreement to the object.
Inheritance can add, modify, or Delete methods, and can add properties.

17. Differences between categories and class extensions.
Answer: The difference between category and extensions is that the latter can add attributes. In addition, the method that the latter adds must be implemented.
Extensions can be thought of as a private category.

What is the difference between the protocols in OC and the interface concepts in Java?
Answer: The agent in OC has 2 meanings, officially defined as formal and informal protocol. The former is the same as the Java interface.
The methods in informal protocol belong to the design pattern and are not required to be implemented, but if implemented, the properties of the class are changed.
In fact, regarding formal agreements, categories and informal agreements I have read about it very early in my studies, and I wrote it in my tutorial.
"The concept of informal agreement is actually another way of expressing a category" Here are some ways you might want to implement, and you can use them to do a better job. "
This means that these are optional. For example, we want a better way, we will declare a category to achieve. Then you can use these better methods directly later on.
In this way, I always feel that the category of this thing is a bit like an optional protocol. ”
Now, in fact, Protocal has begun to unify and standardize the operation of both, because the data said "informal agreement using interface decoration",
Now we see two modifiers in the protocol: "must Implement (@requied)" and "optional implementation (@optional)".

19. What are Kvo and KVC?
Answer: KVC: Key – Value encoding is a mechanism that indirectly accesses an object's properties by using a string to identify the property, rather than by invoking an access method, either directly or through an instance variable.
In many cases, the program code can be simplified. The Apple documentation actually gives a good example.
KVO: A key-value observation mechanism that provides a way to observe a change in a property, greatly simplifying the code.
In particular, to see that one of the places that I used to be is the monitoring of the button click Change state.
Like a button I've customized.
[Self addobserver:self forkeypath:@ "highlighted" options:0 Context:nil];
#pragma Mark KVO
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context {
if ([KeyPath isequaltostring:@ "highlighted"]) {
[Self setneedsdisplay];
For the system is based on the keypath to the corresponding value changes, in theory, and KVC mechanism is the same reason.
For how the KVC mechanism looks for value through key:
"When invoking an object through KVC, such as: [Self Valueforkey" Somekey "], the program automatically attempts to parse the call in several different ways. First find whether the object with Somekey this method, if not found, will continue to find whether the object with Somekey this instance variable (iVar), if not found, the program will continue to attempt to invoke-(ID) Valueforundefinedkey: This method. If this method is not implemented, the program throws a Nsundefinedkeyexception exception error.
( Note: Key-value coding Find method, not only will find Somekey this method, but also find Getsomekey this method, preceded by a get, or _somekey and _ Getsomekey these several forms. At the same time, finding the instance variable will not only look for the variable somekey, but also find out if the _somekey variable exists. )
Design Valueforundefinedkey: The main purpose of the method is that when you use the-(ID) Valueforkey method to request a value from an object, the object can have a last chance to respond to the request before the error occurs. There are many benefits to this, and the following two examples illustrate the benefits of doing so. “
Come to cocoa, this statement should be quite reasonable.
Because we know that the button has a highlighted instance variable. So why do we just add a related keypath on top of that?
Can follow KVC find logical understanding, said the past.

20. What is the role of the agent?
Answer: The purpose of the agent is to change or pass the control chain. Allows a class to be notified to other classes at certain times without having to obtain pointers to those classes. Can reduce the complexity of the frame.
On the other hand, a proxy can be understood as a similarity to the callback listener mechanism in Java.

The type can be modified and not modifiable in OC.
Answer: You can modify the non-modifiable collection class. My personal simple understanding is that you can add changes dynamically and not add changes dynamically.
Like Nsarray and Nsmutablearray. The former in the initialization of the memory control is fixed immutable, the latter can be added, etc., you can dynamically request new memory space.

22. What do we mean by the Dynamic runtime language of OC?
Answer: polymorphic. The main is to postpone the determination of the data type by compile time to the runtime.
This problem actually involves two concepts, runtime and polymorphism.
Simply put, the run-time mechanism allows us to determine the class of an object until run time, and to invoke the class object to specify the method.
Polymorphism: The ability of different objects to respond to the same message in their own way is called polymorphism. It means that a biological class (life) is-eat in the same way;
The human beings belong to the creatures, and the pigs belong to the creatures, and all inherit the life and realize their eat, but the call is the only way we call the Eat method.
That is, different objects respond to the same message in their own way (in response to the Eat selector).
So it can also be said that the runtime mechanism is the basis of polymorphism? ~ ~ ~

23. What are the differences between the notice and the agreement?
Answer: The protocol has a control chain (has-a) relationship, the notification is not.
First of all I didn't quite understand, what is called the chain of control (professional terminology ~). But simple analysis of the notification and agent behavior patterns, we can roughly have their own understanding
In short, it can be a one-to-many message, and a message can be sent to multiple recipient recipients.
Agent according to our understanding, to not directly say not a pair of more, such as we know the Star economic agent, many times an economic person responsible for several star affairs.
Just for different stars, agents of the objects are not the same, each corresponding, it is impossible to say tomorrow to deal with a star to a conference, the agent issued a message to deal with the conference, the nickname B
The press conference. But the notice is not the same, he only cares about giving notice, not caring how much receives interest to deal with.
So the control chain (has-a from English words can be seen roughly, a single ownership and controllable correspondence.

24. Is the push message?
Answer: Too simple, do not answer ~~~~~~~~~~
This is the answer on the cocoa.
In fact, it is not too simple, just too general a concept of things. It's like saying, what is a man.
Push notifications are more of a technology.
A simple point is a means by which a client obtains resources.
In normal cases, the client is active pull.
Push is the server-side proactive push. The implementation of test push allows you to view the blog post.

25. About Polymorphism
Answer: polymorphic, sub-class pointers can be assigned to the parent class.
This topic can actually be found in all object-oriented languages,
Therefore, on polymorphism, inheritance and encapsulation of the basic best have a sense of self-awareness, it is not necessary to write the information on the book can be memorized.
The most important thing is to translate into self-understanding.

26. Understanding of a single case
Answer: 11, 12 The topic actually has a somewhat general feeling, may say is the programming language needs or the essential foundation.
Basically you can write a single case in a familiar language, a scenario you can use, or a frame class that you've encountered in your programming.
Further points, consider the security of how to access a single instance in multithreaded.

27. Talk about the response chain
Answer: The incident response chain. Includes click events, screen refresh events, and more. Propagates from top to bottom or from bottom to top of the view stack.
It can be said that the distribution, delivery and processing of the incident. Specifically, you can look at the touch event this piece. Because the question is too abstract.
Serious doubts about the problem, the more the later the more general.
Can be from the chain of responsibility model, in terms of the incident response chain processing, its own extensibility

What is the difference between frame and bounds?
Answer: Frame refers to the position and size of the view in the parent view coordinate system. (The reference point is the father's coordinate system)
Bounds refers to the position and size of the view in its own coordinate system. (The reference point is its own coordinate system)

29. What is the difference between a method and a selector?
Answer: Selector is the name of a method, which is a combination that contains the name and implementation.
See the Apple documentation for details.

The garbage collection mechanism of OC?
Answer: OC2.0 has garbage collection, but the iOS platform is not available.
Generally we know that objective-c is manual for memory management, but it also has an auto-release pool.
But most of the information, it seems not to be confused with the arc mechanism.

Nsoperation queue?
Answer: The collection class that holds the nsoperation.
Operations and operations queues, which can be seen as the concept of threads and thread pools in Java. A problem that is used to handle iOS multithreaded development.
Some of the information on the Internet mentioned that, although it is a queue, but not with the concept of queuing, put into the operation is not in accordance with the strict advanced show.
There is a doubt here, for the queue, the concept of FIFO is Afunc added into the queue, bfunc tightly followed also into the queue, Afunc first to do this is inevitable,
But Bfunc is waiting for Afunc to complete operation, b just start and execute, so the concept of the queue agitation a bit against the concept of multithreading.
But on the other, I would like to refer to the bank's ticket collection and system.
Therefore, for a than B queue to take the ticket but B first to perform the operation, we can also feel that this is a queue.
But then I saw a vote on the topic of the operation of the queue, one of the sentences mentioned
"Because two operations are committed in close proximity, threads in the thread pool, who start first are uncertain." ”
Instantly think this queue name is a bit of a flicker of people, it is better than pool~
To put it all together, we know that he can be more useful in helping the group with multithreaded programming.

32. What is deferred loading?
Answer: Lazy mode, only in the use of the time to initialize.
Can also be understood as delayed loading.
I think the best is also the simplest of a sample is the TableView in the picture loading shows.
A delay load, to avoid excessive memory, an asynchronous load, to avoid thread congestion.

33. Do you embed two TableView controllers in one view controller?
Answer: A view control only provides a view, theoretically a tableviewcontroller can not put it,
Can only be said to embed a tableview view. Of course, the topic itself is ambiguous, if it is not our qualitative thinking of Uiviewcontroller,
Instead of a macro representation of the view controller, we can think of it as a view control that can control multiple view controllers, such as Tabbarcontroller
That kind of feeling.

34. Can a tableview be associated with two different data sources? What would you do with it?
Answer: First of all, from the code point of view, how the data source Association, in fact, is implemented in the proxy method associated with the data source.
So we don't care how to relate to him, how he relates, and the method just lets me go back and set the data sources as they are relevant to my needs.
So, I think I can set up multiple data sources, but there's a question: What do you want to do? How do you want the list to be displayed, with different data source partition blocks displayed?

35. When to use Nsmutablearray, when to use Nsarray?
Answer: When the array is running in the program, it needs to be constantly changing, using Nsmutablearray, when the array is initialized, it will not change, use Nsarray. It should be noted that the use of Nsarray only indicates that the array does not change at run time, i.e. it cannot add and remove elements to the Nsaarry array, but does not indicate that the contents of elements within its array cannot be changed. Nsarray is thread-safe, Nsmutablearray is not thread-safe, and multithreading is used to nsmutablearray needs attention.

36. Give an example of the delegate method and say the UITableView data source method
Answer: Cocoatouch framework uses a large number of delegates, of which uitableviewdelegate is a typical application of the delegation mechanism, is a typical use of the delegate to implement the adapter mode, where the Uitableviewdelegate protocol is the target, TableView is an adapter that implements the Uitableviewdelegate protocol and sets itself to Talbeview delegate object, which is the adapter, in general, the object is Uitableviewcontroller.
UITableView's data source method has-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section ;
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath;

37. How many Autorelease objects can be created in the app, and is there a limit?
Answer: None

38. If we do not create a memory pool, are there any memory pools available to us?
Answer: The interface thread maintains its own pool of memory, and the user creates a data thread that needs to create a pool of memory for that thread

39. When do I need to create a memory pool in my program?
Answer: A data thread created by the user himself needs to create a memory pool for that thread

40. Which methods of class nsobject are often used?
Answer: NSObject is the base class of Objetive-c, which is composed of NSObject class and a series of protocols.
Class methods Alloc, Class, Description object Methods init, Dealloc, –performselector:withobject:afterdelay: etc. are often used

41. What is a simple construction method?
Answer: The simple construction method is generally provided by the Cocoatouch framework, such as NSNumber + Numberwithbool: + Numberwithchar: + numberwithdouble: + numberwithfloat: + Numberwithint:
Most of the classes in the foundation have a simple construction method, we can get the system to create good objects by the simple construction method, and do not need to release manually.

42. How do I use Xcode to design a common application?
Answer: Use the MVC pattern to design the application, where the model layer completes the detach interface, that is, on the model layer, which is available to run on any device, at the controller layer, based on the iphone and ipad (exclusive Uisplitviewcontroller) Choose different Viewcontroller objects for different features. In the view layer, it can be designed according to the actual requirements, where the Xib file is designed, it is set to universal.

What are the animated effects of UIView?
Answer: There are many, such as Uiviewanimationoptioncurveeaseinout Uiviewanimationoptioncurveeasein uiviewanimationoptioncurveeaseout Uiviewanimationoptiontransitionflipfromleft Uiviewanimationoptiontransitionflipfromright Uiviewanimationoptiontransitioncurlupuiviewanimationoptiontransitioncurldown

44. How do I save data in the iphone app?
Answer: There are several preservation mechanisms:
1. Save on the server via the Web service
2. Save the object in a file by nscoder the curing mechanism
3. Save in the file database via SQLite or CoreData

45. What is CoreData?
Answer: CoreData is an apple that provides a data-saving framework based on SQLite

46. What is a nsmanagedobject model?
Answer: Nsmanagedobject is a subclass of NSObject, is also an important part of CoreData, it is a generic class, to achieve the core data model layer required by the basic functions, the user can be sub-class Nsmanagedobject, Build your own data model.

47. What is Nsmanagedobjectcontext?
Answer: The Nsmanagedobjectcontext object is responsible for the interaction between the application and the database.

48. What is a predicate?
The answer: predicate is through the nspredicate, is through the given logic condition as the constraint condition, completes the filtering to the data.
predicate = [Nspredicate predicatewithformat:@ "CustomerID = =%d", n];
A = [Customers filteredarrayusingpredicate:predicate];

49. What kinds of persistent storage mechanisms are available with CoreData?
Answer: Deposit to file, deposit to Nsuserdefaults (System plist file), deposit to SQLite file database

50. Talk about the understanding of block? and write a uivew animation using block?
Answer: Block is an anonymous function that can get local variables of other functions, which is not only convenient for development, but also can greatly improve the execution efficiency of the application (multi-core CPU can directly handle the block instruction)
[UIView TransitionWithView:self.view
animations:^{[[Blueviewcontroller view] removefromsuperview]; [Self view] insertSubview:yellowViewController.view atindex:0]; }

51. Write down the block definition of the above code.
typedef void (^animations) (void);
typedef void (^completion) (BOOL finished);

52. Try to use + beginanimations:context: And the definition of the block above, write a complete
+ (void) Transitionwithview: (UIView *) View Duration: (nstimeinterval) Duration options: (uiviewanimationoptions) Options animations: (void (^) (void)) animations completion: (void (^) (BOOL finished)) Completion Ns_available_ios (4_0); function execution part of the operation
Answer: None
Network section

53. Does the project involve network access and what objects are used to complete the network function?
Answer: ASIHTTPRequest and Nsurlconnection

54. Brief introduction of the following Nsurlconnection class and + SendSynchronousRequest:returningResponse:error: and –initwithrequest:delegate: The difference between two methods?
Answer: Nsurlconnection is mainly used for network access, where + SendSynchronousRequest:returningResponse:error: is synchronous access to data, that is, the current thread is blocked, and waits for the request to return the response, while –initwithrequest:delegate: using an asynchronous load, when it finishes network access, it passes delegate back to the main thread, and its delegate object.

55. What is multithreading?
Multithreading is a complex concept, in the literal sense is to complete a number of tasks synchronously, improve the use of resources efficiency, from the hardware, operating system, application software from different angles to see, multithreading is given different connotations, for hardware, now on the market most of the CPU is multicore, multi-core CPU operation multithreading more excellent; From the operating system point of view, is a multi-tasking, the current use of the mainstream operating system are multi-tasking, can listen to songs, while writing blogs; for applications, multithreading allows applications to respond faster and respond to user touch actions while the network is downloading. In the iOS application, the first understanding of multithreading is concurrency, it is the original meaning is to do water, then pick vegetables, and then stir-fry the work, will become boiling water to pick vegetables, and finally to stir-fry.

Multi-Threading in IOS
Multi-Threading in iOS, is the cocoa framework of multi-threading, through the cocoa package, can make us more convenient use of threads, C + + students may have more understanding of threads, such as the creation of threads, semaphores, shared variables are aware of, cocoa framework will be much easier, It encapsulates threads, and some packages allow us to create objects that themselves own threads, that is, the thread's object abstraction, thus reducing our engineering, and the robustness of the provider.
GCD is the abbreviation for (Grand Central Dispatch), an easy-to-use multi-threaded class library available at the system level, with runtime features to take advantage of multi-core hardware. GCD API interface for C language functions, function parameters, most of the block, about the use of block see here, provide us with a strong "interface" for the use of GCD see this article
Nsoperation and queue
Nsoperation is an abstract class that encapsulates the implementation of threads in detail, and we can manage multithreaded programs by subclasses of the object, plus nsqueue to object-oriented thinking. See here: A nsoperation-based multi-threaded network Access project.
Nsthread is a control thread execution object, it is not as nsoperation abstract, through which we can easily get a thread, and control it. However, concurrency control between nsthread threads is required to be controlled by ourselves and can be implemented by Nscondition.
See the use of Nsthread for iOS multithreaded programming
Other multithreading
In the framework of cocoa, notifications, timer and asynchronous functions are used in multiple threads (to be supplemented).

57. When does the project choose to use GCD and when to choose Nsoperation?
The advantage of using nsoperation in a project is that Nsoperation is a high abstraction of the thread, using it in the project, will make the program structure of the project better, the sub-class nsoperation design idea, is has the object-oriented advantage (multiplexing, encapsulation), so that the implementation is multi-threaded support, The interface is simple and recommended for use in complex projects.
The advantage of using GCD in a project is that the GCD itself is very simple and easy to use, saving code for uncomplicated multithreaded operations, and the use of block parameters is more readable and recommended for simple projects.

58. What is Block
There are many definitions for closures (blocks), where closures are functions that can read variables inside other functions, which are close to nature and better understood. For the first contact with the block of the classmate, will feel a bit around, because we are accustomed to write such a program main () {Funa ();} Funa () {Funb ();} Funb () {...}; Is the function main called function A, function A called function B ... Functions are executed sequentially, but not in reality, such as project manager M, who has 3 programmers a, B, C, when he gives programmer a to implement functional F1, he does not wait for a to complete, then to arrange B to implement F2, but to arrange for a function F1,b function F2,c function F3, Then maybe write a technical document, and when a has a problem, he will come to the project manager m, when B is done, will notify M, this is an example of asynchronous execution. In this case, block will be able to work, because in the project manager m, to a job, and will also tell a if encounter difficulties, how can find him to report problems (such as hit his mobile phone number), this is the project manager m to a callback interface, to return the operation, such as receiving telephone, Baidu query, Return Web page content to a, this is a block, in M confessed to work, has been defined, and obtained the F1 task number (local variable), but when a encountered a problem, only call execution, cross-function in the project manager m query Baidu, get results back to the block.

The principle of block implementation
Objective-c is an extension of the C language, and the implementation of block is based on pointers and function pointers.
From the development of computational language, the earliest goto, the pointer to the high-level language, to the object-oriented language block, from the machine's thinking, a step closer to human thinking, in order to facilitate developers more efficient, direct description of the logic of Reality (demand).
Here are two great posts to introduce block implementations
Probe into block implementation in iOS
On the realization of Objective-c block
3 Use of block
Working with instances
Block invocation of animation effect under Cocoatouch frame
Use typed to declare block
typedef void (^didfinishblock) (NSObject *ob);
This declares a block of type Didfinishblock,
Then it will be available
@property (nonatomic,copy) Didfinishblock Finishblock;
Declare a BLOKC object, note that the object property is set to copy, and a copy is automatically copied when the block parameter is received.
__block is a special type,
A local variable declared with this keyword can be changed by block, and its value in the original function will be changed.
4 Common series of questions
Interview, the interviewer will first ask, whether to understand the block, whether the use of blocks, these questions equal to the opening, often is the beginning of a series of questions, so be sure to truthfully according to their own circumstances to answer.
1 What are the advantages of using block and using delegate to complete the delegation mode?
The first thing to understand is the delegate mode, which is used extensively in iOS, which is an object adapter in the adapter pattern in design mode, and OBJECTIVE-C uses the ID type to point to everything, making the delegate mode more concise. Learn the details of the delegate model:
iOS design mode-delegate mode
The advantage of using block to implement the delegate mode is that the block code of the callback is defined inside the delegate object function, which makes the code more compact;
An adaptation object no longer needs to implement a specific protocol, and the Code is more concise.
2 Multi-Threading with block
GCD and Block
Using the Dispatch_async series method, the block can be executed in the specified manner
GCD Programming Example
Full definition of Dispatch_async
void Dispatch_async (
dispatch_queue_t queue,
dispatch_block_t block);
Function: Commits an asynchronously executed block in the specified queue, without blocking the current thread
The thread that the block executes is controlled through the queue. The main thread executes the Finishblock object defined in the previous article
Dispatch_async (Dispatch_get_main_queue (), ^ (void) {Finishblock ();});

iOS face questions and answers

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: 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.