The classification mechanism allows you to add new method declarations 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.
# Import "classname. h"
@ Interface classname (categoryname)
@ End
Vector. hCode
# Import <Foundation/Foundation. h>
@ Interface vector: nsobject
{
Double _ vec1;
Double _ vec2;
}
@ Property (nonatomic, assign) Double vec1;
@ Property (nonatomic, assign) Double vec2;
-(Vector *) add :( vector *) V;
-(Void) setvec1 :( double) vec1 andvec2 :( double) vec2;
-(Void) print;
@ End
Vector. m code
# Import "vector. H"
@ Implementation Vector
@ Synthesize vec1 = _ vec1;
@ Synthesize vec2 = _ vec2;
-(Void) print
{
Nslog (@ "V1 value is % F, V2 value is % F", self. vec1, self. vec2 );
}
-(Void) setvec1 :( double) vec1 andvec2 :( double) vec2
{
Self. vec1 = vec1;
Self. vec2 = vec2;
}
-(Vector *) add :( vector *) V
{
Vector * vector = [[vector alloc] init];
Vector. vec1 = V. vec1 + self. vec1;
Vector. vec2 = V. vec2 + self. vec2;
Return vector;
}
@ End
Vector + sub. H code
# Import <Foundation/Foundation. h>
# Import "vector. H"
@ Interface vector (sub)
-(Vector *) sub :( vector *) V;
@ End
Vector + sub. m code
# Import "vector + sub. H"
@ Implementation vector (sub)
-(Vector *) sub :( vector *) V
{
Vector * temp = [[vector alloc] init];
Temp. vec1 = self. vec1-v.vec1;
Temp. vec2 = self. vec2-v.vec2;
Return temp;
}
@ End
Main Code:
Int main (INT argc, const char * argv [])
{
@ Autoreleasepool {
Vector * test1 = [[vector alloc] init];
[Test1 setvec1: 2.2 andvec2: 3.4];
[Test1 print];
Vector * Test2 = [[vector alloc] init];
[Test2 setvec1: 1.1 andvec2: 1.2];
Vector * ret = [test1 Sub: Test2];
[RET print];
[Test1 release];
[Test2 release];
}
Return 0;
}
Result:
17:38:34. 751 access [2057: 303] V1 value is 2.200000, V2 value is 3.400000
17:38:34. 753 access [2057: 303] V1 value is 1.100000, V2 value is 2.200000
Classification is a concept not available in C ++. Classification is implemented through dynamic binding of objective-C. Classification can achieve better performance than inheritance.