先读懂代码才能更好的理解含义。
Demo地址:https://github.com/RainManGO/ExtensionCateGoryProtrolDemo
目录:
Person类没有暴漏任何方法:
//
// Person.h
// ExtensionCateGoryProtrolDemo
//
// Created by apple on 2017/12/14.
// Copyright © 2017年 ZY. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Study.h"
@interface Person : NSObject<Study>
@end
//
// Person.m
// ExtensionCateGoryProtrolDemo
//
// Created by apple on 2017/12/14.
// Copyright © 2017年 ZY. All rights reserved.
//
#import "Person.h"
#import <objc/runtime.h>
//这也是类扩展
@interface Person ()
@property(nonatomic,assign) int age;
@end
@implementation Person
-(void)logAge{
self.age = 18;
NSLog(@"%d",self.age);
}
-(void)Eat{
NSLog(@"Eat");
}
-(void)Study{
NSLog(@"Study");
}
-(void)setFriendName:(NSString *)name{
objc_setAssociatedObject(self, @"friendName", name,OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)friendName{
return objc_getAssociatedObject(self, @"friendName");
}
@end
Category用runtime方法实现了可以设置属性:
//
// Person+Run.h
// ExtensionCateGoryProtrolDemo
//
// Created by apple on 2017/12/14.
// Copyright © 2017年 ZY. All rights reserved.
//
#import "Person.h"
@interface Person (Run)
@property(nonatomic,strong)NSString * name;
-(void)Run;
@end
//
// Person+Run.m
// ExtensionCateGoryProtrolDemo
//
// Created by apple on 2017/12/14.
// Copyright © 2017年 ZY. All rights reserved.
//
#import "Person+Run.h"
#import <objc/runtime.h>
@implementation Person (Run)
-(void)Run{
NSLog(@"Run");
}
-(void)setName:(NSString *)name{
objc_setAssociatedObject(self, @"name", name,OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)name{
return objc_getAssociatedObject(self, @"name");
}
@end
单独的Extension文件相当于一个需要自己实现的Category(本例子已经在Person类实现):
//
// Person+Eat.h
// ExtensionCateGoryProtrolDemo
//
// Created by apple on 2017/12/14.
// Copyright © 2017年 ZY. All rights reserved.
//
#import "Person.h"
@interface Person ()
@property(nonatomic,copy)NSString * friendName;
-(void)logAge;
-(void)Eat;
@end
Protocol和Extension一样需要别人实现,我理解的区别是Extension必须要你扩展的类实现,而protocol谁遵守协议谁实现:
//
// Study.h
// ExtensionCateGoryProtrolDemo
//
// Created by apple on 2017/12/14.
// Copyright © 2017年 ZY. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol Study <NSObject>
-(void)Study;
@end
调用类:
//
// ViewController.m
// ExtensionCateGoryProtrolDemo
//
// Created by apple on 2017/12/14.
// Copyright © 2017年 ZY. All rights reserved.
//
#import "ViewController.h"
#import "Person+Run.h"
#import "Extension/Person+Eat.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person * Mryang = [Person new];
Mryang.name = @"Mryang";
Mryang.friendName =@"MrsLu";
NSLog(@"%@",Mryang.name);
NSLog(@"%@",Mryang.friendName);
[Mryang logAge];
[Mryang Run];
[Mryang Eat];
[Mryang Study];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
打印结果可想而知。见demo