Objective-C magic path [12-classification and Protocol], objective-c12-

Source: Internet
Author: User

Objective-C magic path [12-classification and Protocol], objective-c12-

Master haomeng is devoted to his contribution and respects the author's Labor achievements. Do not repost them.

If the article is helpful to you, you are welcome to donate to the author, support haomeng master, the amount of donation is free, focusing on your mind ^_^

I want to donate: Click to donate

Cocos2d-X source code download: point I send


The classification and protocol are characteristic parts of OC. On the surface, classification is a bit similar to abstract methods in abstract classes (the abstract class concept in C ++ or Java ). The Protocol is similar to the interface (the interface in Java), but it cannot be "Same ".
Category allows you to add a new method declaration to a class file. It does not need to use the subclass mechanism and defines these methods under the same name in the class implementation file. The syntax is as follows: # import "ClassName. h"
@ Interface ClassName (CategoryName)
// Method declaration
@ End category instance

In the previous introduction to polymorphism, we used examples of Vector and Scalar. Below we will add the "Subtract" sub Method to the Vector. Vector + sub. h file
#import <Foundation/Foundation.h>#import "Vector.h"@interface Vector (sub) -(Vector *) sub: (Vector *) v; @end
Vector + sub. m file
#import "Vector+sub.h"@implementation  Vector (sub) -(Vector *) sub: (Vector *) v {Vector *result = [[Vector alloc] init];[result setVec1: vec1 - [v vec1] andVec2: vec2 - [v vec2]]; return result;}@end
Main function called
#import <Foundation/Foundation.h>#import "Vector+sub.h"int main (int argc, const char * argv[]) {Vector *vecA =[[Vector alloc] init];Vector *vecB =[[Vector alloc] init];id result;//set the values[vecA setVec1: 3.2 andVec2: 4.7];[vecB setVec1: 32.2 andVec2: 47.7];// print it[vecA print];NSLog(@" + ");[vecB print];NSLog(@" = ");result = [vecA add: vecB];[result print];[vecA print];NSLog(@" - ");[vecB print];NSLog(@" = ");result = [vecA sub: vecB];[result print];// free memory[vecA release];[vecB release];[result release];    return 0;}
Here, add: In result = [vecA add: vecB] is the original method of the Vector class, And sub: In result = [vecA sub: vecB] is the method of adding a Vector category.
Classification is not defined in object-oriented languages such as Java and C ++. Classification is essentially implemented through dynamic binding of Objective-C. Classification can achieve better results than inheritance.

From the example above, we can see that classification provides a simple method,

It can be used to modularize the class definition to the group or category of the relevant method.

It also provides a simple way to extend existing class definitions, and does not need to parse the source code of the class or create subclass.

# Import "Fraction. h"

@ Interface Fraction (MathOps)

-(Fraction *) add: (Fraction *) f;

-(Fraction *) mul: (Fraction *) f;

-(Fraction *) sub: (Fraction *) f;

-(Fraction *) div: (Fraction *) f;

@ End

Note that this is both the definition of the interface and the extension of the existing interface.

Therefore, the original interface must be included so that the compiler knows the Fraction class.


By convention, the basic names of. h and. m files that are classified are the names of classes followed by the names of classes.

Example: FractionMathOps. m;

Some programmers use the symbol "+" to separate class and category names, such as Fraction + MathOps. h. However, we do not recommend that you name it like this.


Class extension:

Create an unnamed category without specifying a name between the brackets (). This is a special case.

This special syntax is defined as class extension.

The Methods declared in the unnamed class must be implemented in the main implementation area, rather than in the implementation area of separation.

Untitled classification is very useful because their methods are private.

If you need to write a class, and the data and methods are only used by this class, it is more appropriate to not name the class.


Considerations for classification:

Classification can override another method in this class, but it is generally considered as a abuse design habit. Note:

1. After overwriting a method, you can no longer access the original method. (If the override method is required, the correct choice may be to create a subclass .)

Second, adding a new method to a category will not only affect the class, but also affect all its subclasses.

Third, the object/category name pair must be unique. The namespace is shared by program code, libraries, frameworks, and plug-ins.


The Protocol is the same as the Java Interface (Interface) or pure virtual class of C ++, and is used to declare the Interface. The Protocol only defines the list of methods. The protocol is not responsible for implementing methods, so that other classes can be implemented.

Taking the Graphics protocol as an example: Graphics defines the onDraw method, but we carefully analyze what the onDraw method cannot implement. As Graphics (ICS), it cannot know how its subclass draws a graph, it can only specify information such as the onDraw signature and return value, but cannot provide specific implementation. Therefore, Graphics should not be designed as a class but as a protocol.

@ Protocol Graphics
-(Void) onDraw;
@ End
The protocol has only the interface and no implementation, so there is no m file, the keyword @ protocol, the protocol can inherit other protocols, the protocol cannot define member variables.

Ellipse protocol implementation class
#import <Foundation/Foundation.h>#import "Graphics.h"@interface Ellipse:NSObject <Graphics> {}@end
# Import "Ellipse. h" @ implementation Ellipse-(void) onDraw {NSLog (@ "");} @ end
Protocol implementation Triangle
#import <Foundation/Foundation.h>#import "Graphics.h"@interface Triangle:NSObject <Graphics> {}@end
# Import "Triangle. h" @ implementation Triangle-(void) onDraw {NSLog (@ "");} @ end
Code Description: the implementation of the Protocol is after the parent class of the class declaration, plus <Graphics>, different from a single inheritance of the class, the protocol can implement multiple, to implement this protocol, if multiple protocols are to be implemented, separate them with commas (,): <P1, P2>.

Main function called
#import <Foundation/Foundation.h>#import "Graphics.h"#import "Ellipse.h"#import "Triangle.h"int main (int argc, const char * argv[]) {id graphics;graphics = [[Ellipse alloc] init];[graphics onDraw];[graphics release];graphics = [[Triangle alloc] init];[graphics onDraw];[graphics release];    return 0;}

As shown in the preceding example:

The Protocol is a list of methods shared by multiple classes.

The methods listed in the Protocol are not implemented and are planned to be implemented by others.

The Protocol provides a way to define a set of somewhat relevant methods with the specified name.

If you decide to implement all the methods of a specific protocol, it means to comply with (confirm to) or adopt (adopt) this protocol.


Defining a protocol is simple: you only need to use the @ protocol command and then follow the protocol name you provided.

For example:

@ Protocol NSCoping

-(Id) copyWithZone: (NSZone *) zone;

@ End


Two important protocols are mentioned here:

NSCopying
NSCoding

If your class adopts the NSCopying protocol, you must implement the copyWithZone: method.,

By listing the protocol name in a pair of angle brackets (<...>) in the @ interface line, you can tell the compiler that you are using a protocol.

The name of this protocol is placed after the class name and its parent class name,

For example:

@ Interface AddressBook: NSObject <NSCoping>


If your class uses multiple protocols, you only need to list them in angle brackets and separate them with commas (,). For example:

@ Interface AddressBook: NSObject <NSCoping, NSCoding>


If you define your own protocol, you do not have to implement it yourself.

If a class complies with the NSCoping Protocol, its subclass also complies with the NSCoping protocol.

(But it does not mean that these methods are correctly implemented for this subclass ).


@ Required and @ optional keywords

@ Protocol MyProtocol
-(Void) requiredMethod;
@ Optional
-(Void) anOptionalMethod;
-(Void) anotherOptionalMethod;
@ Required
-(Void) anotherRequiredMethod;
@ End

Note that the @ optional command is used here. All methods listed after this command are optional.

@ Required command is followed by the required method.


Note that the Protocol does not reference any class. It is classless ).

Any class can follow the MyProtocol protocol.

You can use conformsToProtocol to check whether an object complies with certain protocols.

For example:

If ([currentObject conformsToProtocol: @ protocol (MyProtocol)] = YES ){

...

}

The dedicated @ protocol command is used to obtain a Protocol name and generate a protocol object.

ConformsToProtocol: The method expects this object as its parameter.


You can use the compiler to check the consistency of variables by adding the protocol name to the angle brackets after the type name.

For example:

Id <Drawing> currentObject;

This tells the compiler that currentObject will contain objects that comply with the Drawing protocol.

If the objects stored in this variable comply with multiple protocols, you can list multiple protocols,

Run the following code:

Id <NSCoping, NSCoding> myDocument;


When defining a protocol, you can extend the definition of an existing protocol.

For example:

@ Protocol Drawing3D <Drawing> the Drawing3D protocol also uses the Drawing protocol.


Finally, classification can also adopt an agreement.

Same as the class name, the protocol name must be unique.


Proxy:

The Protocol is also an interface definition between two classes. Classes that define the Protocol can be seen as the classes that delegate the methods defined by the Protocol to implement them.

Informal (informal) Protocol: a classification that lists a set of methods but does not implement them.

Therefore, informal classification is usually defined for the root class. Sometimes informal protocols are also called abstract protocols.

Informal protocols are actually just a group of methods under a name.

Classes that declare informal protocols do not implement these methods themselves,

In addition, to implement the subclass of these methods, you must re-declare these methods in its interface section,

At the same time, one or more of these methods must be implemented.

Note: The @ optional instruction described above is added to the Objective-C 2.0 language to replace informal protocols.


Merging object:

You can define one or more objects of a class containing other classes.

The object of this new class is the so-called composite object because it is composed of other objects.

The subclass depends on the parent class. Changing the parent class may make the method in the subclass unable to work.



Objective-c: Why protocol?

The objective-c protocol provides public methods for different classes.

The Protocol defines a set of methods without specific implementation. It defines interfaces that other objects have the responsibility to implement. When you implement the Protocol method in your own class, your class complies with this Protocol, and the method declared in the Protocol can be implemented by any class.
Easy to understand
You have written a class. Your class is provided to my class.
I initialized your class instance in my class, so well, you can call your method.
However, your class will call a method when it reaches a certain condition. You don't know who will implement this method, and you don't need to implement it. You just find an interface.
Well, I will call this method when the button is pressed, but I don't care about what to do. I don't know who uses it and who implements it by myself.

Then, define the protocol in your class

@ Protocol yourdelegate

-(Void) dosomething
@ End

Define the id delegate attribute
And in the way you press the button
[Delegate dosomething];

Use your protocol in my class
@ Interface my class: NSObject <yourdelegate>

And when initializing your class, your class. delegate = self;
Then implement your protocol Method
-(Void) dosomething
{Do what you want to do
}

In addition, what you said:
I feel that the Protocol is also used to call methods. Can I instantiate a class and then call the method?

This sentence is wrong in concept. I think you may not be familiar with the protocol. Under what circumstances do you need to use the Protocol.
You need to try several more examples by yourself. First, familiarize yourself with the protocol usage, then think about it, and straighten out the logic.

In objective-c, the Protocol must be used.

The design of the Protocol decouples the relationship between classes

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.