标签:
main.m
Student *stu = [Student studentWithName:@"xiaomin" gender:@"man" age:118]; [stu study]; [stu playGame];
NSString+SayHi.h
@interface NSString (SayHi) //分类(类目,Category),为米有源代码的类,扩充方法,并且只能扩充方法 //一但添加过方法之后,这些方法就是该类自己的方法,由该类的对象或者该类调用 + (void)sayHi; - (void)sayHello; //添加获取首字母的方法,不是大写,改成大写 - (NSString *)changeStringFirstBig; //添加获取尾字母的方法,不是小写,改成小写 - (NSString *)changeStringOverlitter; @end
NSString+SayHi.m
@implementation NSString (SayHi) + (void)sayHi{ NSLog(@"牛比"); } - (void)sayHello { NSLog(@"还是你比"); } - (NSString *)changeStringFirstBig { return [[self substringToIndex:1] uppercaseString] ; } //添加获取尾字母的方法,不是小写,改成小写 - (NSString *)changeStringOverlitter { return [[self substringFromIndex:[self length] -1] lowercaseString]; } @end
Student.h
@interface Student : NSObject { NSString *_name; NSString *_gender; NSInteger _age; } //自定义初始化 - (id)initWIthName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age; + (id)studentWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age; - (void)study; - (void)playGame; @end
Student.m
#import "Student.h" /** * 延展 外部访问不到,只为源代码的类,扩充功能(实例变量,方法),延展中的实例变量以及方法是私有的,只能在本类中访问 如果本类中的某个方法只想在本类中使用,不想让外界调用,那么此时就可以把该方法在本类的.m文件的延展中申明,实现此时,这些方法都是该类的私有方法. OC中,没有绝对的私有 */ @interface Student () { CGFloat _score; } - (void)sayMorning; - (void)sayAfternoon; - (void)sayGoodNight; @end
@implementation Student - (id)initWIthName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age{ if (self = [super init]) { _name = name; _age = age; _gender = gender; } return self; } + (id)studentWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age{ return [[Student alloc] initWIthName:name gender:gender age:age]; } - (void)study { NSLog(@"study 学生苏恶习"); } - (void)playGame{ NSLog(@"学哥屁 去玩"); [self sayAfternoon]; [self sayGoodNight]; [self sayMorning]; } - (void)sayMorning{ NSLog(@"早上好!"); } - (void)sayAfternoon { NSLog(@"下午好"); } - (void)sayGoodNight { NSLog(@"晚安"); } @end
标签:
原文地址:http://www.cnblogs.com/wohaoxue/p/4723689.html