OC中分类
分类创建
分类格式:
- UIColor+ColorChange.h头文件
#import <UIKit/UIKit.h>
@interface UIColor (ColorChange)
// 颜色转换:iOS中(以#开头)十六进制的颜色转换为UIColor(RGB)
+ (UIColor *) colorWithHexString: (NSString *)color;
@end
- UIColor+ColorChange.m文件
#import "UIColor+ColorChange.h"
@implementation UIColor (ColorChange)
+ (UIColor *) colorWithHexString: (NSString *)color
{
}
@end
- 分类是在原有类的基础上添加新的方法。
- 分类不能添加属性。
- 分类如果非要添加属性也是可以的:通过runtime机制的associatedObject。ios分类添加属性
OC中拓展
本质:是分类,只是一种特殊情况。也就是匿名分类。
类扩展格式:
#import "ViewController.h"
@interface ViewController ()//类拓展
@property (nonatomic, strong) UILabel *lable;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
@end
目的:私有属性和方法。
实际中经常把属性和方法写到拓展里,外部类就不能访问。
类别与类扩展的区别:
名称 | 方法 | 属性 |
---|---|---|
类别 | 可以添加 | 不能添加(需要associatedObject) |
分类 | 可以添加 | 可以添加 |
swift中拓展
- 为类拓展属性
extension UIView {
private struct AssociatedKeys {
static var DescriptiveName = "handle"
}
private var eventHanlerColsure : ()->() {
get {
guard let handler = objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? ()->() else {
return {()->Void in
};
}
return handler;
}
set(newHandle) {
objc_setAssociatedObject(self, &AssociatedKeys.DescriptiveName, newHandle, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
}
- 为类拓展方法
- 协议中拓展:为了实现协议的方法。
- 也可以类中添加拓展:进行结构分层。
swift中的拓展不负责私有属性和方法。因为swift的权限有关键词:public、private等等
引用:
网友评论