kvc|, Geneva kvo| delegate| Nsnotification differences

Source: Internet
Author: User
Tags access properties notification center

First, IOS KVC, KVO, Nsnotification, delegate in the actual programming of the use of very much, master their operating principles and the use of the occasion for our program development will bring the effect of the work times;

Second, KVC key-value coding, key value code, level through the key we can find the corresponding value, also can be attached to the corresponding key value. This is similar to our dictionary lookup. For example, we need to find the content of which page, only need to find the dictionary's unique page number (that is, key), we can know the content of this page, according to the dictionary this feature, the program apes invented the dictionary.

Setvalueforkey

Setvalueforundefinekey

Setvalueforkeys

With these methods we can assign a value to the specified key, and the page can assign a value to a key that is not defined in the class.

Since this approach is found and assigned through key values, it does not go through the setter and getter methods, but also You can assign a value to an ID object.

//define a student class, the student attribute has a dog class, the book class#import<Foundation/Foundation.h>#import "TRDog.h"@interfacetrstrudent:nsobject{@private    float_score;} @property (strong,nonatomic) NSString*Name: @property (strong,nonatomic) Trdog*Dog; @property (strong,nonatomic) Nsarray*Allbooks;@end#import "TRStrudent.h"#import "TRBook.h"@implementationtrstrudent-(instancetype) init{if(self=[Super Init]) {Self.dog=[[Trdog alloc]init]; Trbook* book1=[[Trbook alloc]init]; Book1.bookname=@"language"; Book1.bookprice= -; Trbook* book2=[[Trbook alloc]init]; Book2.bookname=@"Math"; Book2.bookprice= -; Self.allbooks=@[book1,book2]; }    returnSelf ;}@end#import<Foundation/Foundation.h>#import<UIKit/UIKit.h>@interfaceTrbook:nsobject@property (strong,nonatomic) NSString*BookName;/*CGFloat can identify the number of bits in the system*/@property (assign,nonatomic) cgfloat bookprice;@end#import "TRBook.h"@implementationTrbook@end#import<Foundation/Foundation.h>@interfaceTrdog:nsobject@property (strong,nonatomic) NSString*name;@end#import "TRDog.h"@implementationTrdog@end
#import "ViewController.h"#import "TRStrudent.h"@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; Trstrudent* stu=[[Trstrudent alloc]init]; /*Assigning a value to a private member variable using KVC*/[Stu setvalue:@98.5Forkey:@"score"];//@98.5 The data for encapsulation[Stu SetValue:@"Zhangshan"Forkey:@"name"]; NSLog (@"name%@", [Stu Valueforkey:@"name"]); NSLog (@"score%@", [Stu Valueforkey:@"score"]); /*Assigning a value to an object of type ID using KVC*/    IDStu2=[[Trstrudent alloc]init]; [Stu2 SetValue:@"Wangwu"Forkey:@"name"]; NSLog (@"name:%@", [STU2 Valueforkey:@"name"]); /*use KVC for hierarchical access to assign values to a student's dog object*/[Stu.dog setValue:@"Wong Choy"Forkey:@"name"]; NSLog (@"Stu.dog name:%@", Stu.dog.name); /*KeyPath can access properties with hierarchical relationships*/[stu2 setValue:@"Huang"Forkeypath:@"Dog.name"]; NSLog (@"STU2 dongname:%@", [STU2 Valueforkeypath:@"Dog.name"]); /*You can use some keywords to quickly return some of the data in an array, or to perform operations on data in a group*/Nsarray* Allbookname=[stu Valueforkeypath:@"Allbooks.bookname"]; NSLog (@"%@", Allbookname); /*Total price of all books*/NSLog (@"%@", [Stu Valueforkeypath:@"[email protected]"]); /*There are a few books in the students*/NSLog (@"totalbooks%@", [Stu Valueforkeypath:@"[email protected]"]); }- (void) didreceivememorywarning {[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.}@end

-"It is not difficult to see through the above code that using KVC can be hierarchical access to multiple key values containing relationships

[Stu2 valueforkeypath:@ "Dog.name"]

-"Use KVC to perform function operations on the value corresponding to the keys contained in the array key

       [Stu valueforkeypath:@ "[email protected]"]  sums the value price of all bookprice in the allbooks array

-"Use KVC to count keys in an array

[Stu valueforkeypath:@ "[email protected]"] Allbooks is an array of attributes, including many books. Use [email protected] to count

Second, KVO, to the property of an object KeyPath add observer, when this property changes, the checker can immediately know. The common APIs are as follows:

1. Register the properties of the object to be observed AddObserver:forKeyPath:options:context:
2. Implement ObserveValueForKeyPath:ofObject:change:context: Method, this method is automatically called when the observed property changes
3. Unregister observation RemoveObserver:forKeyPath:context:

The essence is that during runtime run time, the system will automatically derive a new class nskvonotifying_trsudent, in which the KeyPath set method is overwritten, and a method is added inside.

-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary<nsstring *,id> *) Change context: (void *) context; So just write down the implementation of the method in the parent class, which is automatically executed when a set method that derives from the subclass is run.

/**

Parameter one: the object being observed

Parameter two: the object to be observed

Parameter three: the corresponding property of the object that age needs to observe

Parameter 4:1 Segment property occurs over the hundred years, to monitor the value that the message needs to be passed, whether it is an old value or a new value

Parameter five: additional information sent

*/

[Self.stu addobserver:self forkeypath:@ "age" options:nskeyvalueobservingoptionnew| Nskeyvalueobservingoptionold context:@ "A little older"];

-(void) Observevalueforkeypath: (NSString *) KeyPath Ofobject: (ID) object change: (nsdictionary<nsstring *,id> *) Change context: (void *) Context {

ID newvalue = [object Valueforkey:keypath];

The%@ property of the NSLog (@ "%@ object has changed \ n, the value is as follows: The old value is%@, the new value is:%@, additional information%@", object,keypath,change[@ "old"],change[@ "new"],context);

}

Third, the use of their respective time:

Kvo use time: When the user input view interface has a place to change, we want the model layer to make a certain response and feedback. For example, we need to confirm the user input of the new value and the old value of the time to do some calculation processing. For example, the director's pet's blood release changes when the master's attack was affected. KVO is used to derive new classes, which are less expensive to use than the resource of the program.

Delegate use time: Commonly used in the interface view click Time Interactive action, such as the system UI control is clicked or dragged by the user will start some column response events, similar to the same type of business logic between the response mode, It is better to use delegate. For example, a class has the same business requirements for multiple classes as a boss needs multiple secretaries to collaborate on the tasks it is tasked with, and it is also more appropriate to use proxies. There is has-a control relationship between agent and principal, the execution efficiency is high, and the scale is higher, the drawback is the code is cumbersome, the rules are tedious.

Block use time: Similar to the proxy function of the block, but his poor scale, especially when multiple calls are easily confusing, so long use block between a single two class callback, such as Login registration request Tool class, login registration controller. The Map location request Tool class, and the host controller requests the location class.  This relatively single, simple single callback can use block. -"Through the pre-registration of the heap area function, wait until the time to run to the block, then call, the use of relatively high efficiency, and relatively flexible, poor readability."

Nsnotificaiton: Using the actual, it is often used for some systematic notification, and many classes may need to listen to a certain information, mainly the notification sent to the Broadcast center, through the third-party media broadcast to send a notification message. Receiving his object only needs to be subscribed in the Notification center, which is more suitable for a controller to listen to multiple controllers simultaneously. For example, our Category List column has many sub-controller column list, when these data changes, we need to notify the host controller for interface data Update, if all the applicable protocol, it will cause the program is very complex, the host controller to comply with a variety of protocols, if the use of notifications, It is easy to manage our code), all operations need to rely on three parties to complete, the execution efficiency is slightly inferior to the agent.

kvc|, Geneva kvo| delegate| Nsnotification differences

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.