@fiy-fish
2015-07-18T13:10:40.000000Z
字数 2346
阅读 1407
Objective-c
// main.m// day07-03-类别//// Created by Aaron on 15/7/9.// Copyright (c) 2015年 Aaron. All rights reserved.//#import <Foundation/Foundation.h>//继承//大量创建相似的类//统一接口//继承官方或者第三方的类//继承扩展类-----实际上产生了一个新的类//类别//主要作用:扩展一个类 -----实际上是给原来的类增加一些东西//副作用: 将方法进行分类管理//分工合作/*@interface 原类名 (类别名)@end@implementation 原类名 (类别名)@end*/// 扩建了 NSString 类 添加一个让字符串逆序的方法@interface NSString (Reverse)//{// NSInteger _age;//}+(void)showString:(NSString *)string;-(NSString *)reverseString;@end@implementation NSString (Reverse)-(NSString *)reverseString{NSString *str = @"";for(NSInteger i = self.length-1; i >= 0; i--){unichar c = [self characterAtIndex:i];//不可变字符串也可以添加字符str = [NSString stringWithFormat:@"%@%C",str,c];}return str;}+(void)showString:(NSString *)string{NSLog(@"%@",string);}@end//1.类别里面可以扩展方法//2.可以扩展实例方法和类方法//3.在类别里,不能添加属性//4.要使用类别中的方法,需要包含类别的头文件//5.在类别中可以使用原类的属性//6.但是在.m里定义的私有属性是不能在类别中直接访问的//7.在类别里面可以访问原类的方法//8.要访问原类的属性或者方法都必须是在原类的interface里提供了接口才能访问//9.类别里面可以实现一些私有的方法//10.类别里方法的优先级比较高, 子类类别>子类>父类类别>父类//11.类别里重写原类的方法,可以不声明接口//12.父类类别的方法,子类依然适用,但是要包含头文件#import "Person.h"#import "Person+Eat.h"#import "Student.h"int main(int argc, const char * argv[]) {@autoreleasepool {NSLog(@"%@",[@"hello" reverseString]);[NSString showString:@"world"];Person *p = [[Person alloc] init];[p singSongs];Student *std = [[Student alloc] init];//[std playLOL];[p eatFan];NSLog(@"-------------");[std eatFan];[std singSongs];}return 0;}
#import "Person.h"@interface Student : Person@end
#import "Student.h"@implementation Student@end
#import "Person.h"@interface Person (Eat)-(void)eatFan;//-(void)playLOL;@end
#import "Person+Eat.h"@implementation Person (Eat)-(void)eatFan{[self singSongs];NSLog(@"%@要吃饭",_name);//_age = 100;//[self playLOL];[self naKuaiZi];}-(void)naKuaiZi{NSLog(@"拿筷子");NSLog(@"%@",_name);}-(void)singSongs{NSLog(@"person+Eat 唱:-海阔天空");}@end
#import <Foundation/Foundation.h>@interface Person : NSObject{NSString *_name;}-(void)singSongs;//-(void)playLOL;@end@interface Person (Play)@end
#import "Person.h"//匿名类别//专门用来声明内部接口//匿名类中可以添加属性@interface Person ()@property (nonatomic,assign)NSInteger age;@end@implementation Person//添加属性//{// NSInteger _age;//}-(instancetype)init{if(self = [super init]){_name = @"小新";}return self;}-(void)singSongs{[self playLOL];self.age = 1000;NSLog(@"person 唱:我是一只小小小鸟");}-(void)playLOL{NSLog(@"打撸啊撸");// [self singSongs];// NSLog(@"%ld",self.age);}@end@implementation Person (Play)-(void)playLOL{NSLog(@"Person (Play)打你妹啊,就知道撸");}@end
