------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------
The use of category to add some new methods to the class dynamic can ensure that the data of the original class is added and then extended This does not need to create subclasses in the simplest way to implement the method of the class the different class methods are controlled to the classification file. Example: #import <Founation\Founation.h>//Create a class @interface student:nsobject-(void) study; @end #import "Student.h" @implementation student-(void) Study{nslog (@ "hard study"); } @synthesize age=_age; @end Add New method for Student class Dynamics #import "Student.h"/ /import student.h. Cannot use @class to prevent extended method names from being duplicated with extended class method names &NBSP ; @interface Student (Test) -(void) sport; @end #import "student+test.h" @implementation -(void) Sport{ nslog (@ "Basketball and football"); } @end #import " STUDENT.M " #import" STUDENT+TEST.M "//the. h file to import the classification method void main () { @aotoreleasepool {Student *stu=[[[ Student alloc] init] Autorelease]; [stu Study]; [stu sport];//succeeded in calling the expanded method } } Print results: hard Studey basketball and football usage scenarios: When a project needs to change and does not want to change the schema of the original class The project size is large, the use of classification is more Effective maintenance and management use of @protocol is the proxy mode A list of methods that declare methods that can be implemented by any class #import < foundation/foundation.h> @class Button; @protocol buttondelegate <NSObject>//defines a protocol and complies with the NSObject protocol -(void) OnClick: (Button *) btn;//ways to implement protocols @end @interface button:nsobject @property (nonatomic,retain) id<buttondelegate > Delege; The proxy class -(void) click; Hit button notification yourself was clicked @end #import "Button.h" @implementation button -(void ) Click{ [_delegate onclick:self]; } -(void) dealloc{[_delegate release];[ Super dealloc]; } @end //come in #import <Foundation/Foundation.h> @protocol buttondelegate; @interface mylinter:nsobject<buttondelegate>//User Compliance Agreement @end # Import "MyLinter.h" #import "Button.h" @implementation mylinter//implements the Protocol -(void) OnClick: (Button *) Btn{ nslog (@ " I was hit by%@ ", BTN);//click the button } @end #import <foundation/foundation.h> # Import "BOOTTON.M" #import "MYLINTER.M" void Main () { @autoreleasepool {Button *button=[[[button alloc ] init] autorelease]; mylinter *lin=[[[mylinter alloc] init] Autorelease]; [button onclik:button];//hit the button Be notified } } Run results: I've been hit.
Black Horse Programmer--category and Protocol protocol