1. Why should I have a category? Extending on the basis of existing classes can be implemented using both inheritance and composition, but why does OC have to have categories like this?
Consider a scenario where a dictionary is created, key is a string, and value is the length of the string. The general practice is to:
Nsmutabledictionary *dict = [nsmutabledictionary dictionary]; nsstring* str = @ "Hello"; nsnumber* NUM1 = [nsnumber numberwithunsignedint:[str length]]; [Dict setobject:num1 forkey:str]; str = @ "World"; NUM1 = [nsnumber numberwithunsignedint:[str length]]; [Dict setobject:num1 forkey:str]; NSLog (@ "%@", dict);
Since the nsmutabledictionary stored key-value must be an OC object and cannot store basic C-language types such as int, the object value in the above dict must be of type nsnumber, and each storage length is called nsnumber* NUM1 = [nsnumber numberwithunsignedint:[str length]] This line of repeating code, the category can be used to solve such problems.
In addition to some non-source classes, such as the NSString class, inherit from NSString is a bad choice, because you do not know how nsstring internal implementation, NSString will be based on different initialization of the internal creation of different objects, the category can solve the problem.
2. Category The individual feels like the global function in C, like the above example, can pass in a length and return a nsnumber* object. Method of declaring a type: Add the category name after the class and enclose it in parentheses.
@interface NSString (numberconvenience)
-(NSNumber *) Lengthasnumber;
@end
Numberconvenience implementation is simple
@implementation NSString (numberconvenience)-(NSNumber *) lengthasnumber{ Nsuinteger length = [self length]; return ([NSNumber numberwithunsignedint:length]);} Lengthasnumber@end
Using the protocol to resolve the 1 duplicate code problem is as follows:
Nsmutabledictionary *dict = [nsmutabledictionary dictionary]; nsstring* str = @ "Hello"; [Dict setobject:[str Lengthasnumber] forkey:str]; str = @ "World"; [Dict setobject:[str Lengthasnumber] forkey:str]; NSLog (@ "%@", dict);
The code is more simple and easy!!!
3. Category pros and cons.
Category defect: 1) Unable to add Member variable 2) is prone to name collisions. When a name conflicts with a method in a category that has a high priority, he will overwrite other names with the same name to become visible.
Category benefits: 1) You can spread the implementation code across different files or frameworks. 2) Create a reference to the Private Method 3) Add an informal protocol to the object (informal protocol)
OBJECTIVE-C Basic 6: Categories category