(a) A brief introduction
1.Delegate (agent, delegate) agent is almost the most commonly used in iOS development, appdelegate in the project is the use of this design pattern, not only that, there are many native controls also use this design pattern, such as: uitextfiled, UITableView and so on. The official explanations are as follows:
Delegation is a simple and powerful pattern in which one object in a program 1 acts on behalf of, or in coordination with, Another object. The delegating object keeps a reference to the other object-the Delegate-and at the appropriate time sends a message to it . The message informs the delegate of an event, the delegating object is about to handle or have just handled. The delegate respond to the message by updating the appearance or state of itself or other objects in the application, And in some cases it can return a value this affects how an impending event is handled. The main value of delegation is the it allows-easily customize the behavior of several objects in one central Obje Ct.
The use of the method no longer an example (online about the delegate base use of countless examples), mainly summarizes the advantages and disadvantages of delegate.
Pros: 1. Reduce the coupling of the code, so that event monitoring and event processing are separated. 2. Clear syntax definition, reduce maintenance costs, strong code readability. 3. You do not need to create a third party to listen for events and transfer data. 4. A controller can implement multiple agents to meet the custom development requirements, optional must have greater flexibility.
Cons: 1. The code process to implement the delegate is cumbersome. 2. When cross-layer value monitoring is implemented, the coupling of the code is increased, and the hierarchy of the program becomes chaotic. 3. The delegate's ease-of-use will be greatly reduced when multiple objects are simultaneously passed the value response.
2.NotificationCenter (notification) Notifications are also commonly used in iOS development, such as MPMoviePlayerController in the avfoundation framework to monitor playback state changes, It is also the notificationcenter that is used when playing events such as stopping. The official explanations are as follows:
An Nsnotificationcenter object (or simply, Notification Center) provides a mechanism for broadcasting information within a Program. An Nsnotificationcenter object is essentially a notification dispatch table.
Objects register with a notification center to receive notifications (Nsnotification Objects) using the Addobserver:select Or:name:object:or AddObserverForName:object:queue:usingBlock:methods. Each invocation of this method specifies a set of notifications. Therefore, objects may register as observers of different notification sets by calling these methods several times.
Each running COCOA program has a default notification center. You typically don ' t create your own. An Nsnotificationcenter object can deliver notifications is within a single program. If you want to post a notification to other processes or receive notifications from other processes, use an instance of NS Distributednotificationcenter.
Nsnotification Adopt A single case design mode, when a key is registered to the Notification center, then no matter where the notification center to send a message of this key, then the implementation of the communication value, the registered notification object will call the corresponding method.
Pros: 1. Easy to use, code Lite. 2. Resolves a problem that listens to multiple objects at the same time. 3. The transfer value is convenient and quick, the context itself carries the corresponding content. Cons: 1. After use, always remember to write off the notice, otherwise unforeseen crash will occur. 2.key is not secure enough, the compiler does not monitor whether it is handled correctly by the notification hub. 3. The tracking of actions during commissioning will be difficult. 4. When the user sends a notification to the notification center, no feedback will be given. 5. A third-party object is required to act as an intermediary between the listener and the listener.
3.Block (code block) block is an extension of the C language introduced by ios4.0+ and Mac OS X 10.6+ to implement the features of anonymous functions. Apple's official explanation for block is also very concise:
A block is an anonymous inline collection of code, and sometimes also called a "closure". Blocks is a powerful c-language feature that's part of COCOA application development. They is similar to ' closures ' and ' lambdas ' you'll find in scripting and programming languages such as Ruby, Python, and Lisp. Although the syntax and storage details of blocks might at first glance seem cryptic, you'll find that it ' s actually quite Easy to incorporate blocks into your projects ' code.
A closure is a function that accesses variables inside other functions. The use of block here is also not repeating (I do not know the students can point this link, I think written in very detailed). Whether it's a native frame or a third-party framework, we can see the block, and the powerful functionality and ease of use of the block make it well-liked by architects.
The official also has a short guidance document, interested students can take a look (official guidance). It is important to note that several blocks are used in this document as well.
- Callback processing at task completion
- Message Listener Callback Processing
- Error callback Handling
- Enumeration callback
- View animations, transformations
- Sort
Pros: 1. The syntax is concise, the implementation callback does not need to display the calling method, the code is more compact. 2. Enhance the readability and maintainability of your code. 3. Cooperate with GCD to solve multithreading problem.
Disadvantage: 1.Block in the code will automatically do a retain operation, easy to cause memory leaks. The default reference in 2.Block is a strong reference, which can easily cause circular references.
(ii) Precautions
1. Agent
- When the method is called in the proxy, the child thread of the system is used, so when using delegate for UI operations, the main thread method of GCD must be called: Dispatch_async (Dispatch_get_main_queue (), <^ ( void), block> the UI operation code that is written in the block.
2. Notice
- The reason for crash in the use of the notification is that many of the cases are registered observers that do not have a timely logout of the observer, although this situation is more common in the non-arc era, but that is not to say that this problem will not occur in the current Arc era. Often once the problem is difficult to track down, so still have to develop the habit of timely write-off.
- Because of the extremely simple use of notifications, it is often possible to see many developers abusing nsnoticationcenter during the development process. Causes a lot of clutter around the notifications, code maintainability and readability is very poor, even if the use of macro definitions can not completely avoid these problems. For example, when debugging, when there are multiple observe, it is simply to the feeling of human life, want to die of heart have. In this respect, block and delegate are much stronger than notification.
3.Block
- When referencing an external variable in a block, the block will only have a read-only copy inside it, which means that even if you modify the value of that external variable before using block, its value is still the value of the first external variable in the block you are using. If you want to synchronize the value of an external variable, then you need to prefix the variable with the __block keyword when referencing it inside the block.
- Block itself is like an object can be retain, and release. However, when the block is created, its memory is allocated on the stack (stack), not on the heap (heap). His own domain is the scope at the time of creation, and once it is created, calling block will cause the program to crash.
(iii) Comparison of usage scenarios
1. Callback methods in the daily development process, we often encounter a number of completed processing problems, such as the completion of the network request after the callback, or after the completion of the page load callback. At this time we generally use the first two methods, block or delegate. In a one-to-one transmission callback, the use of block is more simple and efficient, just need to perform the required operation in the code block. In a one-to-many situation, delegate is more able to play its own advantages.
2. Cross-layer communication sometimes we need to implement communication between two unrelated objects, which is bound to increase the coupling of the code if we use block or delegate, which is unhealthy for the structure of the code. So using notification at this time is a wise choice.
3.UI Response event users will always need an interactive response from the app when interacting with the app's UI, and there's no doubt that the proxy design pattern is used. And Apple's official advice is also certain, in the cocoa touch framework we can also in almost all UI interactive control of the header file to see the delegate member variables, it is confirmed that the UI response to events delegate has an absolute advantage.
4. Simple to pass when it is necessary to make a simple and worthwhile pass, such as when the child control is transferred to the Indexpath clicked by the parent control, it is more suitable to use block to pass the value. Because, if just to pass this a simple value and no special business processing and define a protocol, and then implement the Protocol, set the agent re-write method will be very troublesome, not worth the candle, this time the simple and efficient block can be a perfect alternative to delegate complete the task.
iOS Development Delegate,notification,block Usage Tips