Learning ios--Classification and understanding of protocol Protocal

Source: Internet
Author: User

1. Classification (category) concept and use

If we have used C #, we all know that C # has a thing called extension function, can not inherit the existing class, the existence of the class to add some of the original interface functions, OBJECTIVE-C classification concept and this is very similar, even can be said that the same type of things, Although it is not known who is the first person to appear, the introduction of this thing, can make the programming aspect more rich and efficient.

OBJECTIVE-C provides a different way of--category, which can dynamically add new behavior to existing classes. This ensures that the original design of the class is small and gradually expands as the function increases. When you use category to extend a class, you do not need to access its source code, and you do not need to create subclasses. Category uses a simple way to implement the modularity of the relevant methods of the class, assigning different class methods to different classification files. However, it is important to note that category does not extend properties to classes, because object C does not support such a property extension.

The definition syntax for classification (category) is as follows.

?
1 2 3 @interface ClassName (CategoryName)  @end

  

It seems as if they have a conventional habit of naming both the declaration file and the implementation file name uniformly in the "original class name +category" way. So the OC function is similar to C #, but this is not the same as C #, C # no matter where you put it, but we still should respect its rules.

For example, our definition of adding an extension method to the Xyzperson class is as follows, and the function contract for this definition is placed in the file "Xyzperson+xyzpersonnamedisplayadditions.h".

?
1 2 3) 4 5 #import "XYZPerson.h"    @interface XYZPerson (XYZPersonNameDisplayAdditions) - (NSString *)testMethod;@end

Then its implementation code is shown below, and its code conventions are put into "xyzperson+xyzpersonnamedisplayadditions.m".

?
1 2 3 4 5 6 7 #import "Xyzperson+xyzpe RsonNameDisplayAdditions.h "     @ Implementation xyzperson (xyzpersonnamedisplayadditions) -( nsstring *) TestMethod {      return [ nsstring stringwithformat:@ "%@,%@" self .lastname, self .firstname]; } @end

In C #, extension methods are namespace-related, and once you jump out of the scope of the namespace, this extension function is not working, and objective-c, like the class, does not have a namespace concept, so you need to be cautious when extending, Otherwise, the interfaces that are susceptible to categorization conflict with the class itself. For this reason, the Apple recommendation is also to add a prefix to the classified interface, and the naming takes on the usual rules of the interface, as shown in the following code.

?
1 2 3 @interface NSSortDescriptor (XYZAdditions) + (id)xyz_sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending;@end

This extension method name is a bit longer, but basically ensures that there is no conflict with normal interface methods.

Usage Scenarios for Category:

1. When you define a class, in some cases (such as a change in requirements), you may want to add a method to one or more of these classes. 2. A class contains many different methods that need to be implemented, and these methods require members of different teams to implement 3, and when you are using classes in the underlying class library, you might want these classes to implement some of the methods you need. With these requirements, the category can help you solve the problem. Of course, there are some problems with category, 1, category can access the original class instance variables, but cannot add variables, if you want to add variables, you can consider to create subclasses through inheritance. 2, category can overload the method of the original class, but it is not recommended to do so, the consequence is that you can no longer access the original method. If you do overload, the correct choice is to create a subclass. 3, and the common interface is different, in the implementation of the classification of the file can not implement all the declared method, as long as you do not call it.

There is also the ability to become a class extension, which is the case for a class that has code, that is, your class code and the source of your extension is compiled at the same time.

The class extension method is similar to the above classification, they do not need to write the extension classification of the name, which is somewhat like the concept of anonymous extended classification, as shown below

?
1 2 3 @interface ClassName ()  @end
2. Protocol Protocal

This concept to a large extent and C # interface similar, but it is different, it can be an optional implementation interface @optional, there is a required implementation interface @required, although objective-c inside already has a keyword @interface, But there's a difference between this and protocal.

Like the interface of C #, this protocol can inherit from another protocal, that is, they can have an inheritance relationship.

?
1 2 @protocol NewProtocal   <Protocal>@end

  

Because of the many applications developed by OBJECTIVE-C, such as iOS, they use the proxy model extensively in the MVC development model, and this protocal handles the relationship well. In iOS and OS X development, Apple employs a number of proxy models to achieve the decoupling of view and controller in MVC.

For example, all events generated by UIView are entrusted to the controller. According to the Convention, the framework suffix delegate is protocol, such as Uiapplicationdelegate,uiwebviewdelegate.

In C # There are many such as iclonable, IEnumerable such interface, as long as the implementation, you can implement cloning and enumeration, in Objective-c, this is can use protocal to replace, if a protocol inherits NSObject, Then this is the agreement represented herein, is the NSObject agreement of the Derivative agreement (not the NSObject Class), that is, the context of the understanding NSObject is a protocol, if it is in the @interface inheritance, then that is the NSObject object. It's a little interesting.

The following is an optional and required protocol definition example.

?
1 2 3 4 5 6 7 8 9 @protocol XYZPieChartViewDataSource - (NSUInteger)numberOfSegments; - (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex; @optional - (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex; - (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex; @required - (UIColor *)colorForSegmentAtIndex:(NSUInteger)segmentIndex; @end

Since the protocol is optional and required, if we want to know whether a dynamic object has an interface function, it is judged by the @selector operator.

?
1 2 3 4 nsstring *thissegmenttitle; &NBSP;&NBSP;&NBSP;&NBSP; if ([ self .datasource respondstoselector: Code class= "OBJC keyword" > @selector (Titleforsegmentatindex:)]) { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; thissegmenttitle = [ self .datasource Titleforsegmentatindex: index]; &NBSP;&NBSP;&NBSP;&NBSP;

Like the C # interface definition, a class object of Objective-c can implement many protocols, the following example is the case where a class's interface defines the implementation of several protocols.

?
1 2 3 @interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol> ...@end

This enables the MyClass object to have only one base class object, but can implement multiple protocols (C # is multiple interfaces).

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.