OC provides the ability to extend the method of the class without modifying the source code of the class, the "classification" category, which is similar to the extension method in C #, generally used in the inconvenient to modify the source code of the class (such as OC System related library), but there is a need to extend the method of the class, you can use classification to achieve.
There should be no mechanism available in Java, but Java can implement AOP through dynamic proxies, execute code logic before and after Pointcuts, and personally think it is more convenient than OC.
girl.h//10_category////Created by Apple on 14/12/23.//Copyright (c) 2014 CC. All rights reserved.//#import <Foundation/Foundation.h> @interface girl:nsobject//Display the Chinese name of MM-(nsstring*) Showenglishname, @end////girl.m//10_category////Created by Apple on 14/12/23.//Copyright (c) 2014 CC. All rights reserved.//#import "Girl.h" @implementation girl-(nsstring*) Showenglishname {return @ "MM";} @end ////girl+girlcategory.h//10_category////Created by Apple on 14/12/23.//Copyright (c) 2014 CC. All rights reserved.//#import "Girl.h"//oc the header file//naming Specification base class + class name. h/.m//format @interface base class (classification)//function of the classification: on the basis of not modifying the base class source file, A dynamic extension method for the base class//By classifying categories you can add some extension methods to these classes without modifying the OC or iOS framework's source code//classification is not the way subclass inherits, but instead directly extends the base class @interface Girl (Girlcategory) Add a method to display Chinese names to the Girl class-(nsstring*) showchinesename; @end////girl+girlcategory.m//10_category////Created by Apple on 1 4/12/23.//Copyright (c) 2014 CC. All rights reserved.//#import "Girl+girlcategory.h" @implementation Girl (girlcategory)-(Nsstring*) Showchinesename {return @ "Meimei";} @end////main.m//10_category////Created by Apple on 14/12/23.//Copyright (c) 2014 CC. All rights reserved.//#import <Foundation/Foundation.h> #include "Girl.h" #include "girl+girlcategory.h" int main (int argc, const char * argv[]) {@autoreleasepool {girl* pgirl = [[Girl alloc] init]; Girl the method defined in the base class NSLog (Pgirl.showenglishname); Method of extension in Girlcategory classification NSLog (pgirl.showchinesename); } return 0;}
Category Objective-c Categories