// // main.m // OCdemo-07-01-CateGory // // Created by lanou3g on 15/10/15. // Copyright (c) 2015年 Object. All rights reserved. // #import <Foundation/Foundation.h> #import "NSString+SayHi.h" #import "NSDate+NowDate.h" #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { NSString *string = @"强强"; //调用类目添加的方法 [string sayHi]; NSString *nowDate = [NSDate nowDate]; NSLog(@"nowDate = %@",nowDate); Person *person = [[Person alloc]init]; [person eat]; [person call]; } return 0; }
person.h
// // Person.h // OCdemo-07-01-CateGory // // Created by lanou3g on 15/10/15. // Copyright (c) 2015年 Object. All rights reserved. // #import <Foundation/Foundation.h> @interface Person : NSObject { NSString *_name; } -(void)eat; -(void)call; @end
person.m
// // Person.m // OCdemo-07-01-CateGory // // Created by lanou3g on 15/10/15. // Copyright (c) 2015年 Object. All rights reserved. // #import "Person.h" // 延展,声明私有的方法和实例变量 @interface Person () { //声明私有的实例变量 NSString *_phoneNumber; } // 声明私有方法 -(void)privateMoney; @end @implementation Person -(void)eat{ NSLog(@"大黄爱吃翔"); } -(void)call{ _phoneNumber = @"110"; NSLog(@"打电话%@",_phoneNumber); } -(void)privateMoney{ NSLog(@"私房钱"); } @endNSDate+NowDate.h
#import <Foundation/Foundation.h> @interface NSDate (NowDate) //获取当前时间 +(NSString *)nowDate; @endNSDate+NowDate.m
#import "NSDate+NowDate.h" @implementation NSDate (NowDate) //获取当前时间 +(NSString *)nowDate{ NSDate *date = [NSDate date]; //设置时间格式 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"]; return [dateFormatter stringFromDate:date]; } @endNSString+SayHi.h
#import <Foundation/Foundation.h> //类目: 通过类目 Category 给一个类添加方法,添加的方法,会成为原类的一部分,从而达到扩展一个类的功能 @interface NSString (SayHi) //添加方法 -(void)sayHi; @endNSString+SayHi.m
#import "NSString+SayHi.h" @implementation NSString (SayHi) -(void)sayHi{ NSLog(@"我是通过Category添加的方法"); } @end