Nsnotification, KVC and KVO

Source: Internet
Author: User
Tags notification center

Notice

Know:

Nsnotification objects encapsulate information so the it can be broadcast to other objects by an nsnotificationcenter obj Ect. An Nsnotification object (referred to as a notification) contains a name, an object, and an optional dictionary. The name is a tag identifying the notification. The object is an any object that the poster of the notification wants to send to observers of that notification (typically, I T is the object that posted the notification). The dictionary stores other related objects, if any. Nsnotification objects is immutable objects.
A notification object contains some information so that it can be broadcast to other objects through a notification hub object, a message notification object (a notification) that contains a name, an object, and an operation dictionary. The name is an identifier for the notification object, which can be any object, as long as the notification sender wants to send to the notifying observer (in short, the notification sender). If there are, some related objects are stored in the dictionary. Nsnotification objects are immutable objects.


You can create a notification object with the class methods NotificationWithName:object:or NotificationWithName:object:us Erinfo:. However, you don ' t usually create your own notifications directly. The Nsnotificationcenter methods PostNotificationName:object:and PostNotificationName:object:userInfo:allow Conveniently post a notification without creating it first.
Can be done by Notificationwithname:object: or notificationWithName:object:userInfo: However you do not have to go directly to create your own notifications. Methods for notification hubs Postnotificationname:object: and PostNotificationName:object:userInfo: Allows you to send a notification before you create it easily.


use the notification must ensure that before sending to register a good notice, or no object can receive this notice.


Nsdictionary *dict = @{@ "name": @ "Lius", @ "age": @12};
Nsnotification *first = [nsnotification notificationwithname:@ "Firstnotification" object:self userInfo:dict]; To create a notification object for self, the self will issue a notification

[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (receivenotification) name:@ " Firstnotification "Object:nil"; Add notifications to notification hubs, so there's a way to receive notifications from self
[[Nsnotificationcenter Defaultcenter] postnotification:first]; Send a notification


Contrast: NotificationWithName:object:userInfo and AddObserver:selector:name:object
Two name: Refers to the same object, the name of the notification, the first one is to create a notification, give the notification name, and the second is to add a listener to listen to a notification. If the second name is nil, it is not judged by this.
Two object: Represents the notification object that is emitted by the object, the first creates a notification, creates a notification for an object, and the second is a notification sent over to listen for an object.


Notification Center


1. Notification Center:
Notification hubs are essentially a mechanism for providing message broadcasts within a program. Notification hubs cannot communicate between processes. is actually a setter that forwards the message to the desired object, based on the internal message forwarding. Notification hubs is based on the observer pattern, which allows you to register and delete observers.
A nsnotificationcenter can have a lot of notification messages nsnotification, for each nsnotification can have a lot of observers observer to receive notifications.


2. Notification hubs two important classes
Nsnotificationcenter: This is the soul of the notification hub in iOS, which implements the observer pattern and provides the developer with an interface such as registering, deleting the Observer, We can get an instance of it through a single example (there is only one Nsnotificationcenter instance object inside a program).
Nsnotification: This is the carrier of the message, through which the message content can be passed to the observer. which Name identifies the message name, and object is typically the sender itself, and dictionary is the message content that is passed.


3. Use of notification hubs
When we register the observer for a message, if we have the corresponding message, the observer receives the corresponding message and expands the processing. It is important to note that when you finish using the message, you do not want to receive the message, you need to remove the observer, or an error will occur.


Add opportunity: When you want to listen to messages
Time to remove: When the message is finished, you do not want to receive the message again. An error occurs if you do not remove the information when you do not need it.


Registration notice: Where to receive notifications
-(void) Addobserver: (ID) notificationobserver
Selector: (SEL) Notificationselector
Name: (NSString *) notificationname
Object: (ID) notificationsender
Parameters:
Notificationobserver: An object of the registered observer, the value must not be nil (generally controller)
Notificationselector: The method explicitly describes this information, the recipient sends a notification listener * * *. This method specifies that only one parameter can be passed, and this parameter is an instance of the Nsnotification type. In simple terms, it is a callback method.
Notificationname: The name of the registered observer's notification that only the notification of this name will be transmitted to the observer. If a nil is passed in, the Notification center will not use the name of the notification to decide whether to pass in a notification to its observer.
Notificationsender: This object is used to indicate which object the observer wants to receive notifications from, and if a nil notification center is passed in, it will not use a notification sender to decide whether to send a notification to its observers. In simple terms, who sent the notice?


Notice Points of Note:
If Addobserver:selector:name:object is called: Note that you must call RemoveObserver:name:object before the observer or the related object is destroyed:




Example:


SELF.P1 = [[Person alloc] init];
SELF.P2 = [[Person alloc] init];

Nsdictionary *dict = @{@ "name": @ "Lius", @ "age": @12};
Nsdictionary *dict2 = @{@ "name": @ "Hua", @ "age": @13};

object is the name of this notification to add a notification to an object, and the addition of the two is for later monitoring to prepare, listening to know which object to listen to or which notification of which object.
Nsnotification *first = [nsnotification notificationwithname:@ "Firstnotification" Object:self.p1 userinfo:dict]; SELF.P1 notifies the content of the dictionary Dict
Nsnotification *second = [nsnotification notificationwithname:@ "Secondnotification" Object:self.p2 UserInfo:dict2];

Self.first = First;
Self.second = second;

Add a listener: name is the notification, object is a notification, and if name and object are nil All notifications will be heard
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (receivenotification:) Name:nil Object:nil ];
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (receivenotification:) name:second.name Object:nil];


-(void) Click
{

Send two notifications, but only a few objects can be received
[[Nsnotificationcenter Defaultcenter] postNotification:self.first];
[[Nsnotificationcenter Defaultcenter] postNotification:self.second];


}


-(void) dealloc
{
[[Nsnotificationcenter Defaultcenter] removeobserver:self];
}


KVC


Nskeyvaluecoding, an informal protocol, provides a mechanism to indirectly access the properties of an object. KVO is one of the key technologies based on KVC implementation.
Understanding: An object has certain properties. For example, the person object has a name and address property. In KVC's view, the person object has a value corresponding to its name and the key value of Adderss key is a string, and its corresponding value can be any Odgar object. At the most basic level, KVC has two methods: one is to set the value of key and the other is to get the value of key.


Using the KVC accessor (getter) method
NSString *originalname = [P valueforkey:@ "name"];


Using the KVC accessor (setter) method
[P setvalue:@ "NewName" forkey:@ "name"];


If person has another key spouse (spouse), spouse's key value is another person object, which can be written in KVC
NSString *spousesname = [P valueforkeypath:@ "Spouse.name"];


Note: Key and keypath to distinguish, key can get the value from an object, and KeyPath can use a number of keys "." Split to connect "as above example: equivalent to
[[P valueforkey:@ "spouse"] valueforkey:@ "name"];


Use Setvaluesforkey Note: When using the Setvaluesforkeywithdictionary function, if the value in the dictionary is more than the member variable, you need to consider setting Setvalue:forundefinedkey:  And in Pugmkh, a few extra keys in the dictionary are called several times. and the attribute and key to be consistent, otherwise it will not match, if the dictionary key is name, then the attribute is @property (nonatomic,copy) NSString *name;


KVO


Key-value Observing (KVO) is built on the KVC, and it is able to observe the change of the KVC key path value of an object,
There are three ways to take note: One is to add a listener, one to be processed after hearing the change, and the last to remove the listener. If you have more objects to listen to, you can remove the listener by placing it in the array and then removing the listener into the order. If you remove it, you'll be crash.


The system framework already supports KVO, using the following steps:
1. Register, specify the attributes of the viewer.
2. Implementing a callback method
3. Removal of observations


Example:
-(void) viewdidload
{
[Super Viewdidload];
name = @ "Sea line";
Price = 10.0;

UILabel *pricelabel = [[UILabel alloc] Initwithframe:cgrectmake (20, 80, 80, 30)];
Pricelabel.text = [NSString stringwithformat:@ "%.2f", Price];
[Self.view Addsubview:pricelabel];
Self.mylabel = Pricelabel;

Added to the value of the listener
[Self addobserver:self forkeypath:@ ' price ' options:nskeyvalueobservingoptionnew | Nskeyvalueobservingoptionold Context:nil];


UIButton *button = [UIButton buttonwithtype:uibuttontypecustom];
Button.frame = CGRectMake (30, 190, 130, 50);
[Button addtarget:self action: @selector (Btnclick) forcontrolevents:uicontroleventtouchupinside];
[Button settitle:@ "click" Forstate:uicontrolstatenormal];
[Button Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];
[Self.view Addsubview:button];

}


The supervisor hears the object change and starts executing this method
-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary *) Change context: (void *) Context
{
if ([KeyPath isequaltostring:@ "Price"]) {
Self.myLabel.text = [NSString stringwithformat:@ "%.2f", Price];
}
}


-(void) Btnclick
{
NSNumber *value = @ (arc4random ()% 80);
[Self setvalue:value forkey:@ ' price '];


}


Release in Dealloc


-(void) dealloc
{
[Self removeobserver:self forkeypath:@ ' price '];
}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Nsnotification, KVC and KVO

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.