1 KVO (Key-value observing)
Is the notification mechanism that provides the property of the object being changed. The implementation of KVO in the foundation, many foundation-based frameworks are dependent on it. If you are interested only in changing the value of an object. You can use KVO message delivery. Prerequisites for satisfying KVO: 1 The recipient (the object that receives the notification of the object change) needs to know the sender (the object whose value will change); 2, the recipient needs to know the sender's life cycle, because it needs to unregister the observer before the sender is destroyed. If both requirements are met, the message delivery mechanism can be one-to-many (multiple observers can register the change of the same object)
If you want to use KVO on core Data, there is a slight difference in the method. This is related to the lazy loading (faulting) mechanism of core data, which, once a managed object is lazily loaded, will be set to the appropriate observer, even if its properties have not been changed.
Note: The attribute values are first taken into the cache and then accessed once the object is required, which is the default behavior in Core Data, which is called faulting. Doing so avoids reducing memory overhead, but you can disable faults to improve performance if you are sure that the specific property values of the resulting object will be accessed.
2 Notice (Notification)
The notification mechanism is a good tool for passing messages in two unrelated modules in your code. Notification mechanism broadcast messages that are especially useful when the message is rich and you don't have to expect the recipient to pay attention
Notifications can be used to send arbitrary messages, and can even contain a userinfo dictionary. You can inherit nsnotification to write a custom behavior of your own notification class, which is unique in that the sender and the recipient do not need to know each other, so notifications can be used to pass messages between different modules that are far apart. This means that the delivery of this message is one-way and we cannot respond to the notification/
3 Delegate (delegation)
Delegation in the framework of Pingguo, it allows us to customize the behavior of the object, and receive a number of triggered events, to use the delegation mode, the sender needs to know the recipient, but in turn there is no requirement, should be the sender only need to know that the recipient conforms to a certain protocol, So they both have a very loose combination.
Any method should be defined for the delegation protocol, and we can deliver the message according to our own needs. The content of the message can be delivered using method parameters, and delegation can respond to the sender in the form of a square regret. If you just pass the message between the relatively close two modules, delegation is a very flexible and straightforward message-passing mechanism.
Excessive use of delgation also poses risks. If the sonata is so tightly coupled that no one of the objects can work alone, then there is no need to use the delegate protocol. In these cases, the object already knows the type of the individual to communicate directly
Blocks (block)
Block was recently added to Objective-c, and was first seen on OS X 10.6 and IOS 4 platforms. Blocks can often completely override the role of the delegation messaging mechanism. However, both of these mechanisms have their own unique needs and advantages.
A reason for not using blocks is usually that the block will have the risk of causing the retain ring (retain cycles). If the sender needs to retain block but is not sure when the reference is assigned nil , then all references within the block will have a self potential retain loop.
Suppose we want to implement a selection method in a table view that uses a block callback instead of a delegate mechanism, as follows:
Self.myTableView.selectionHandler = ^void (Nsindexpath *selectedindexpath) {//processing selection};
The problem here is that it self will retain table view,table view in order for the block to be able to use it and then need to retain the block. However, table view cannot set this reference to nil because it does not know when the block is needed. If we cannot guarantee breaking the retain ring and we need retain sender, then block is not a good choice.
NSOperationis a good example of using block. Because it breaks the retain ring in certain place, solves the above problem.
Self.queue = [[Nsoperationqueue alloc] init]; Myoperation *operation = [[Myoperation alloc] init]; Operation.completionblock = ^{[self finishedoperation];}; [Self.queue addoperation:operation];
At first glance, it seems that the above code has a retain ring: self retain Queue,queue retain operation, operation retain, Completionblock CK retain self . However, adding operation to the queue causes operation to be executed at some time and then removed from the queue. (If not executed, the problem is big.) Once the queue has removed the operation, the retain ring is broken.
Another example is that we are writing a class of video encoders, in which we call a encodeWithCompletionHandler: method. For the sake of the problem, we need to make sure that the Encoder object releases a reference to the block at a certain point in time. Its code is as follows:
@interface Encoder () @property (nonatomic, copy) void (^completionhandler) (), @end @implementation encoder-(void) Encodewithcompletionhandler: (void (^) ()) handler{ Self.completionhandler = handler; Do asynchronous processing ...} This method is called once after completion-(void) finishedencoding{ self.completionhandler (); Self.completionhandler = nil; <-don't forget this!} @end
Once the task is completed and the completion block has been called, we should set it to nil .
If a called method needs to send a one-time message as a reply, then using block is a good choice because we can break the potential retain loop. In addition, it is difficult to refuse to use block for processing if the processed message and the call to the message are put together to enhance readability. In use cases, it is common to use blocks to perform callbacks, false callbacks, or similar things.
Target-action
Target-action is a typical way of delivering messages when responding to UI events. UIControl NSControl This mechanism is supported on IOS and on Mac NSCell . Target-action establishes a loose relationship between the sender and receiver of the message. The recipient of the message does not know the sender, and even the sender of the message does not know what the recipient of the message will be. If Target is nil , the action is passed down in the response chain (responder chain) until it finds an object that responds to it. In IOS, each control can even be associated with more than one target-action.
One limitation of the target-action-based delivery mechanism is that messages sent cannot carry customized information. The first parameter of the action method on the MAC platform is always the receiver. In IOS, you can selectively put the sender and the event that triggered the action as parameters. There is no other way to control the content of the action message.
Make the right choice
Based on the characteristics of the different message delivery mechanisms described above, we have drawn a flowchart to help us make different choices in different contexts. A word of advice: The flowchart proposal does not represent the final answer. There are times when other choices can still achieve the desired results. But in most cases this picture will guide you in making the right decision.
Some of the details in the diagram are worth a dig:
A box says: The sender supports KVO. This is not just about sending a KVO notification when the value changes, but also stating that the viewer needs to know the sender's life cycle. If the sender is in a weak attribute, then the sender is likely to become nil himself, when the observer causes a memory leak.
A box in the last line says that the message responds directly to the method call . This means that the receiver of the method invocation needs to give the caller a message as a direct feedback of the method invocation. This means that the code that processes the message and the code that invokes the method must be in the same place.
Finally, in the lower right corner, a selection branch says: can the sender ensure that a reference to the block is released? This involves the problem of potential retain loops that we discussed before about Block's API. If the sender does not guarantee that a reference to the block will be released at a certain point in time, you will be in trouble with the retain ring.