IOS_OC_Category, iosoc
1. Category Overview
What are the application scenarios of Category:
1. The class contains many methods to implement, and these methods need to be implemented by members of different teams.
2. When you are using the classes in the base class library, you do not want to inherit these classes but just want to add some methods.
Category can meet the above requirements. Of course, you need to pay attention to the following issues when using Category:
1. Category can access the instance variables of the original class, but cannot add instance variables. If you want to add variables, You can inherit to create subclass.
2. Category can reload the methods of the original class. It is not recommended to do so. This will overwrite the methods of the original class. If you do need to overload it, you can create a subclass by inheriting it.
3. What is different from a common interface is that the instance method in the Category implementation file does not need to implement all declared methods as long as you do not call it.
2. Instance
@interface NSString (PLUS)- (int)numberCount;@end@implementation NSString (PLUS)- (int)numberCount{ int count = 0; NSUInteger len = [self length]; for (int i=0; i<len; i++) { unichar ch = [self characterAtIndex:i]; if(ch>='0' && ch<='9'){ count++; } } return count;}@end
#import <Foundation/Foundation.h>#import "NSString+PLUS.h" //importint main(int argc, const char * argv[]){ NSString *s = @"ad7a8da9d9a1d1"; NSLog(@"%@ len = %d", s, [s numberCount]); return 0;}
3. Role of category
(1) The implementation of classes can be distributed to multiple different files or multiple different frameworks to facilitate code management. You can also provide class extensions to the Framework (without the source code, you cannot modify it ).
(2) create a forward reference to a private method: if the methods in other classes are not implemented, the compiler reports an error when you access the private methods of other classes, declare these methods in the class (without having to provide method implementation), the compiler will not generate a warning
(3) add informal protocols to an object: Create an NSObject class called "create an informal protocol" because it can be used as a delegate object of any class.