Category
OC provides a different way of adding new behaviors (methods) to existing classes dynamically.
This ensures that the original design of the class is small and gradually expands as the function increases.
And when you use the category to extend a class, you do not need to create subclasses.
Category uses a simple way to implement the modularity of the relevant methods of the class, assigning different class methods to different classification files.
You can feed any class to add new methods, including those that do not have source code to the class.
It is customary to place category codes in separate files, usually named in the style "class name + category name".
Now we add a category hello to the NSString class. Steps such as:
1 file-new-new File, or press command+n shortcut key to eject.
2 Select Objective-c File and click Next. Pop:
3 fill in the category name Hello, select the type of file that Category,class fill to which class to add the category to.
after that, two files are created: nsstring+hello.h and NSSTRING+HELLO.M.
Nsstring+hello.h
#import <Foundation/Foundation.h> @interface NSString (Hello)-(void) haha; @end
NSSTRING+HELLO.M
#import "Nsstring+hello.h" @implementation nsstring (Hello)-(void) haha{ NSLog (@ "nsstring haha");} @end
you need to import the header file of the category where you use it
#import <Foundation/Foundation.h> #import "nsstring+hello.h" typedef int (^mysum) (int, int), int main (int argc, const char * argv[]) { @autoreleasepool { NSString *str = @ "abcdef"; [str haha]; } return 0;}
The output is:
2016-08-11 17:42:25.622 command Line project [6126:275845] nsstring haha
You can add as many categories as you want for any class, and of course ensure that the category name is unique.
Defects:
1 You cannot add a new instance variable in the category, you can add a property.
2 Name conflict: The methods in the category have the same names as the existing methods, at which time the categories have higher precedence.
Objective-c Category