From: http://blog.csdn.net/pjk1129/article/details/6458644
This article introduces the new properties of objective-C language, where category allows you to add your own methods to existing classes, the Protocol is a special Inheritance Method in objective-C language, similar to interfaces in Java. Next, I will first introduce their functions and analyze them with examples in the project.
I. Category
Sometimes we need to add some methods to a defined class, instead of rewriting the class. For example, when the project is already large,CodeA large number of methods, or many methods are included in the class. When other code calls this class to create an object and use this class method, you can use this class to expand the new method.
Note: classes can only be extended, rather than member variables.
Instance analysis:
1. Purpose: In my project, I need to compress the image. In this case, I want to extend the uiimage class by category and increase the image compression method.
2. Category definition:
Category. h declaration File
# Import<Foundation/Foundation. h>
@ InterfaceUiimage (uiimageext)
// This method is the image compression method I added.
-(Uiimage*) Imagebyscalingandcroppingforsize :(Cgsize) Targetsize;
@ End
Category. m implementation file
# Import"Uiimageext. H"
@ ImplementationUiimage (uiimageext)
-(Uiimage*) Imagebyscalingandcroppingforsize :(Cgsize) Targetsize
{
Uiimage* Sourceimage =Self;
Uiimage* Newimage =Nil;
CgsizeImagesize = sourceimage.Size;
CgfloatWidth = imagesize.Width;
CgfloatHeight = imagesize.Height;
CgfloatTargetwidth = targetsize.Width;
CgfloatTargetheight = targetsize.Height;
CgfloatScalefactor =0.0;
CgfloatScaledwidth = targetwidth;
CgfloatScaledheight = targetheight;
CgpointThumbnailpoint =Cgpointmake(0.0,0.0);
If(Cgsizeequaltosize(Imagesize, targetsize) =No)
{
CgfloatWidthfactor = targetwidth/width;
CgfloatHeightfactor = targetheight/height;
If(Widthfactor> heightfactor)
Scalefactor = widthfactor;// Scale to fit height
Else
Scalefactor = heightfactor;// Scale to fit width
Scaledwidth = width * scalefactor;
Scaledheight = height * scalefactor;
// Center the image
If(Widthfactor> heightfactor)
{
Thumbnailpoint.Y= (Targetheight-scaledheight )*0.5;
}
Else If(Widthfactor
{
Thumbnailpoint.X= (Targetwidth-scaledwidth )*0.5;
}
}
Uigraphicsbeginimagecontext(Targetsize );// This will crop
CgrectThumbnailrect =Cgrectzero;
Thumbnailrect.Origin= Thumbnailpoint;
Thumbnailrect.Size.Width= Scaledwidth;
Thumbnailrect.Size.Height= Scaledheight;
[SourceimageDrawinrect: Thumbnailrect];
Newimage =Uigraphicsgetimagefromcurrentimagecontext();
If(Newimage =Nil)
Nslog(@ "Cocould not scale image");
// Pop the context to get back to the default
Uigraphicsendimagecontext();
ReturnNewimage;
}
@ End
3. How to Use the Category I have extended the uiimage above. The following shows how to call this method in my project:
//Based on the ImageTagShow Image
-(Void) Showphotobyserialnumber :(Int) Imagetag;
{
// This largeimagearray is nsmutablearray type. It stores the image storage path and obtains the uiimage according to the path.
Uiimage* IMG = [Uiimageimagewithcontentsoffile:[Self.LargeimagearrayObjectatindex: Imagetag];
//Myscrollview is my custom scrollview, which aims to make scrollview respond to click events. I will elaborate on how to customize the scrollview in a later blog
Myscrollview* Scrview = [[Myscrollview Alloc]Initwithframe:Cgrectmake(340* Imagetag,0,320,480)];
Scrview.Host=Self;
// This indicates that the class is called, and imagebyscalingandcroppingforsize is called through the uiimage instance object.: Category
Scrview.Image= [ImgImagebyscalingandcroppingforsize:Cgsizemake(320.0,480.0)];
Scrview.Tag= Imagetag +100;
// Insert the above scrview to the imagescrollview. The imagescrollview is of the uiscrollview type.
[Self.ImagescrollviewAddsubview: Scrview];
[ScrviewRelease];
}
Ii. Agreement
Similar to interfaces in Java, Protocol defines a set of methods without specific implementation, Only those"Compliance"(Conform)Or"Use"(Adopt)TheseProtocolClass to provide their own implementation. The Protocol is not the class itself. They only define 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.
1. The syntax structure of the protocol is as follows:
@ ProtocolProtocolname // protocol name
Methoddeclaration ; // Method name
@ End 2. How to use the Protocol The syntax for class declaration is as follows:
@ InterfaceClassname:Parentclassname<Protocolname>
Then, in the implementation file of this class, the method to implement this ProtocolMethoddeclaration
3. instance analysis
The following describes how to use the Protocol in my project. Here we only need to talk about my own protocol.
1) Purpose of the instance: To enable the uiimageview on the scrollview to respond to the Click Event
2) Protocol definition:
Define the protocol in the. h declaration file of the class
# Import<Foundation/Foundation. h>
// The imagetouchdelegate Protocol
@ ProtocolImagetouchdelegate
// Method declared in the Protocol
-(Void) Imagetouch :(Nsset*) Touches withevent :(Uievent*) Event whichview :(ID) Imageview;
@ End
@ InterfaceImagetouchview:Uiimageview{
ID<Imagetouchdelegate> Delegate;
}
@ Property(Nonatomic,Assign)ID<Imagetouchdelegate> Delegate;
@ End
The. m implementation file for this class is as follows:
# Import"Imagetouchview. H"
@ ImplementationImagetouchview
@ SynthesizeDelegate;
-(ID) Initwithframe :(Cgrect) Frame
{
If(Self= [Super Initwithframe: Frame])
{
[SelfSetuserinteractionenabled:Yes];
}
ReturnSelf;
}
-(Bool) Touchesshouldbegin :(Nsset*) Touches withevent :(Uievent*) Event incontentview :(Uiview*) View
{
Returnyes;
}
-(Void) Touchesbegan :(Nsset*) Touches withevent :(Uievent*) Event
{
[Delegateimagetouch: TouchesWithevent: EventWhichview:Self];
}
@ End
3) how to use the Protocol?
I have defined imagetouchdelegate. How can I use this protocol? When a class uses this protocol, you can list the protocol name in the class declaration. If you want to use multiple protocols, separate them with commas (,) in the brackets. When the class adopts this protocol, it must be declared in addition to the. h file, and the methods in the declared protocol must be implemented in its. m implementation file. The preceding example demonstrates how to implement the Protocol in my project.
In my class, first use the imagetouchdelegate protocol in the. h declaration file.
# Import<Uikit/uikit. h>
// Introduce the header file of the definition protocol imagetouchdelegate
# Import"Imagetouchview. H"
// Place the protocol name in the angle brackets behind the parent header. If multiple protocols exist, separate them with commas (,).
@ InterfacePhotoonshotviewcontroller: uiviewcontroller<Imagetouchdelegate> {
}
@ End
The following describes how to implement the Protocol definition in the. m implementation file of the class.
# Import"Photoonshotviewcontroller. H"
@ ImplementationPhotoonshotviewcontroller
// Implement the methods defined in the Protocol,
-(Void) Imagetouch :(Nsset*) Touches withevent :(Uievent*) Event whichview :(ID) Imageview {
}
@ End
Categories and protocols are widely used and useful in iOS development. It is necessary to master them!
Now, the simple application of categories and Protocols has been described. If you have any questions, please feel free to contact us!