Objective-C basic notes (4) Category
OC provides a distinctive way-Category, which can dynamically add new behaviors (methods) for existing classes. This ensures that the original design scale of the classes is small, when the function is added, it is gradually expanded.
When you use Category to expand a class, you do not need to create a subclass. Category uses a simple method to modularize the related methods of the class, allocate different class methods to different classification files.
The following uses three classification examples to show how to use classification:
Next, we will create a Student Test category in the previous code. The creation process is as follows:
Note that the Student + Test. h and Student + Test. m files above are the classification files we created for the Student class.
Student + Test. h file
#import "Student.h"@interface Student (Test)- (void)test;@end
Student + Test. m file
# Import "Student + Test. h" @ implementation Student (Test)-(void) test {NSLog (@ "Call the Test method of Student's test Classification");} @ end
Main. m file
#import
#import "Student.h"#import "Student+Test.h"int main(int argc, const char * argv[]) { @autoreleasepool { Student *stu = [[[Student alloc] initStudent:23] autorelease]; [stu test]; } return 0;}
Running result:
11:32:00. 861 memory management [582: 33690] Students of age 23 created
11:32:00. 862 memory management [582: 33690] called the Test method of Student's test Classification
11:32:00. 862 memory management [582: 33690] Students of age 23 are released
In addition to this writing method, you can directly write it to Student. h and Student. m without creating a file separately. We can also classify the system class (NSString). For example, we can add a json processing method to NSString.
#import
@interface NSString (JSON)+ (void)json;@end
#import "NSString+JSON.h"@implementation NSString (JSON)+ (void) json{ NSLog(@"{'nam':'CodeingSnal', 'age',24");}@end
Classification scenarios:
1. When defining a class (for example, requirement change), you may need to add new methods to one or more classes.
2. A class contains many different types of methods to be implemented, which need to be implemented by members of different teams.
3. When using the basic class library class, you may want these classes to implement some methods you need, such as writing an NSString + JSON file. h. Expand some JSON parsing methods for the NSString class.