1. Category)
The classification in object-C is a compilation method that allows us to expand a class by adding a method (but new instance variables cannot be added through category ), and we do not needCodeThis is similar to defining attributes using prototype in JavaScript.
We can create a new method for a class without editing the class definition in the code.
The following is an example of defining and using categories.ProgramThe following code adds the camelcasestring category to nsstring in object-C. The space in a string can be removed by using the camelcasestring method, and rewrite the words after the original space into uppercase (convert the string to the hump type ).
# Import <Foundation/Foundation. h>/* the classification process can be roughly divided into the following steps: Step 1: Create a new file with an interface, create an existing class. Step 2: add the methods and methods to be extended to the new file. That is, the class to be added * // nsstring indicates the class name to be added, this class must already exist. // Camelcase is the name of the method added for the class. // You can only add methods, but not variables. // Naming convention for header files: classname + categoryname. h @ interface nsstring (camelcase)-(nsstring *) camelcasestring; @ end @ implementation nsstring (camelcase)-(nsstring *) camelcasestring {// call the internal method of nsstring to obtain the hump string. // Self points to the class of the added category. Nsstring * castr = [self capitalizedstring]; // creates an array to filter out spaces and combines characters using separators. Nsarray * array = [castr componentsseparatedbycharactersinset: [nscharacterset whitespacecharacterset]; // output nsstring * output = @ ""; for (nsstring * word in array) {output = [Output stringbyappendingstring: Word];} return output ;}@ endint main (INT argc, const char * argv []) {NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init]; nsstring * STR = @ "My name is Bill. "; nslog (@" % @ ", STR); STR = [STR camelcasestring]; nslog (@" % @ ", STR); [pool drain]; return 0 ;}
2. Extension)
You can understand that extension is an anonymous classification. The following is an example of extension:
@ Interface myclass: nsobject-(float) value; @ end @ interface myclass () {// note here: Extended float value;}-(void) setvalue :( float) newvalue; @ end @ implementation myclass-(float) value {return value;}-(void) setvalue :( float) newvalue {value = newvalue;} @ end