Category)['K processing Ti processing equipment Ri]N. Category, category; Category
Definition: Add a new method to an existing class
I. Declaration category
The Declaration format of a category is similar to that of a category, as follows:
@ InterfaceNsstring (numberconvenience )//Convenience[K then n' VI: NJ then ns]N. convenience; toilet; convenience-(Nsnumber *) Lengthasnumber;@ End
This statement has the following features:
1. The existing class is located behind the @ interface keyword. This method adds a class named numberconvenience to the nsstring class.(Note: ensure that the category name is unique.)
2. You can add classes of other classes (nsstring in this example, you can also add other classes) and methods. Don't ask. End with @ end.
Difference from a class: instance variables cannot be declared in a class.
II. Implementation category
@ ImplementationNsstring (numberconvenience)-(Nsnumber *) Lengthasnumber {unsignedIntLength =[Self length];Return([Nsnumber numberwithunsignedint: length]);}@ End
Note: The lengthasnumber method uses [self length] to obtain the string length.
Eg:
Create a new nsmutabledictionary Class Object and add a string and its length as the key and value respectively.
Int Main ( Int Argc,Const Char * Argv []) {ngutoreleasepool * Pool; Pool = [[NSAID utoreleasepool alloc] init]; nsmutabledictionary * Dict; dict = [Nsmutabledictionary dictionary]; [dict setobject :[ @" Hello " Lengthadnumber] forkey: @" Hello " ]; Nslog ( @" % @ " , Dict); [pool release]; Return ( 0 );}
No Mac running result (no bug) is 5
Iii. Limitations and functions
Limitations:
1. You cannot add new instance variables to the class;
2. Naming is prone to conflict. Simply put, the method name in the category must be the same as the existing method name. When a conflict occurs, your category method will replace the initial method (the category has a higher priority)
Purpose:
1. Implement classes in multiple different files or different frameworks
2. Create a forward reference to a private MethodObjects of the class cannot be declared in the forward reference, nor can they be used in inline member functions. Only the pointers, references, function parameters, and return types of the class can be declared.
3. Add informal protocols to objects
Note:Informal protocol (Interface)Protocols in OC and interfaces in C (Interface) Difference: the interface in C # Must be implemented. Otherwise, an error is reported during compilation. Although obj-C will warn during compilation, it can finally be compiled.
Protocal): The semantics is more intense: the class that requires the Protocol to be used, "must" implement the methods agreed in the Protocol