The category is a class, which is an existing class with new features added.
Category is used to add a new method to an existing class. You can use the object of the existing class to call the added method without inheriting the existing class.
The classification class can distribute the implementation of classes in multiple files.
There cannot be a variable in the category, and the class does not contain the location of the variable.
If the method in the class is the same as the method name in the class, this will cause a conflict, and the class method will completely replace the class method.
Different classes of the same class declare the same method, which will lead to instability, and which method will be called is uncertain.
CATEGORY statement:
# Import "classname. H"
@ Interface classname (categoryname)
Method Declaration
@ End
CATEGORY implementation:
# Import "classname + categoryname. H" // declare the file
@ Implementation classname (categoryname)
Method implementation
@ End
Instance:
Fractionmath. h
# Import "fraction. H"
@ Interface fraction (math)
-(Fraction *) Add: (fraction *) F;
-(Fraction *) Mul: (fraction *) F;
-(Fraction *) Div: (fraction *) F;
-(Fraction *) Sub: (fraction *) F;
@ End
Fractionmath. m
# Import "fractionmath. H"
@ Implementation fraction (math)
-(Fraction *) Add: (fraction *) f {
Return [[fraction alloc] initwithnumerator: numerator * [f denominator] + denominator *
[F numerator] denominator: denominator * [f denominator];
}
-(Fraction *) Mul: (fraction *) f {
Return [[fraction alloc] initwithnumerator: numerator * [f numerator]
Denominator: denominator * [f denominator];
}
-(Fraction *) Div: (fraction *) f {
Return [[fraction alloc] initwithnumerator: numerator * [f denominator]
Denominator: denominator * [f numerator];
}
-(Fraction *) Sub: (fraction *) f {
Return [[fraction alloc] initwithnumerator: numerator * [f denominator]-denominator * [f numerator]
Denominator: denominator * [f denominator];
}
@ End
Main. m
# Import <stdio. h>
# Import "fraction. H"
# Import "fractionmath. H"
Int main (INT argc, const char * argv []) {
// Create a new instance
Fraction * frac1 = [[fraction alloc] initwithnumerator: 1 denominator: 3];
Fraction * frac2 = [[fraction alloc] initwithnumerator: 2 denominator: 5];
Fraction * frac3 = [frac1 Mul: frac2];
[Frac1 print];
Printf ("*");
[Frac2 print];
Printf ("= ");
[Frac3 print];
Printf ("/N ");
// Free memory
[Frac1 release];
[Frac2 release];
[Frac3 release];
Return 0;
}
Output
1/3*2/5 = 2/15
Form: http://student.csdn.net/space.php? Uid = 121497 & Do = Blog & id = 46861