the practical function of category is to add methods to existing classes. The methods added for the existing classes can be implemented without implementation and can be implemented again when needed. How do we implement category in our actual code ? For example, the person class in our previous article.
. h ////////////////#import <Foundation/Foundation.h> @interface person:nsobject @ Property (nonatomic,copy) NSString *name, @property (nonatomic,assign) int age; @property (nonatomic,assign) NSString * Sex -(void) printinfo; @end ///////////////// m ////////////////#import "Person.h" @implementation Person@synthesize name = _name,sex = _sex; @synthesize age = _age; -(void) Printinfo { NSLog @ My name is:%@ I am a%@%@ this year, Self.name,self.age,self.sex,nsstringfromclass ([Self class ]));} @end
Now that there is no Driving method in the existing person class, let's add Driving to it, and we'll create a new. h and. m file with a name called Person+driving (class name + method name), so naming has a benefit, It's just a glance to know what kind of method is added to the class.
. h //////////////////////#import <Foundation/Foundation.h> #import "Person.h" @ Interface Person (person_driving)-(void) Driving; @end/////////////////// . M //////////////////////#import "Person+driving.h" @implementation person (person_driving)-(void) Driving { NSLog (@ "Last night Tesla did not charge, today is BMW X6");} @end
Let's take a look at the test appdelegate and add the tests.
#import "AppDelegate.h" #import "Teacher.h" #import "Student.h" #import "Person.h" #import "Cleaner.h" #import "person+ Driving.h "@interface appdelegate () @end @implementation appdelegate-(BOOL) Application: (UIApplication *) application Didfinishlaunchingwithoptions: (nsdictionary *) launchoptions {person *p = [[Person alloc] init]; P.name = @ "The old king next door"; P.age =; P.sex = @ "male"; [P printinfo]; [P driving]; return YES;} @end
Test results:
2015-06-07 22:34:22.247 attendance[15791:2195987] My name is: Next door old Wang this year I am a man
2015-06-07 22:34:22.248 attendance[15791:2195987] Tesla didn't charge last night, and today it's BMW X6 .
This site article is for baby bus SD. Team Original, reproduced must be clearly noted: (the author's official website: Baby bus )
Reprinted from "Baby bus Superdo Team" original link: http://www.cnblogs.com/superdo/p/4559609.html
[Objective-c] 005_ category (categories)