1.首先在分类文件中导入头文件
#import <objc/runtime.h>
2.实现代码如下:
(1).h定义文件
#import <UIKit/UIKit.h> @interface UIView (Category) /* * 基本数据类型 */ @property (nonatomic,assign) CGFloat offset; /* * 对象类型 */ @property (nonatomic,copy) NSString *name; /* * 结构体(CGPoint) */ @property (nonatomic,assign) CGPoint point; @end
(2).m实现文件
#import "UIView+Category.h"
#import <objc/runtime.h>
static NSString *offsetKey = @"offset";
static NSString *nameKey = @"name";
static NSString *pointKey = @"pointKey";
@implementation UIView (Category)
/*
* 添加基本数据类型需要转化为NSNumber类型
*/
- (void)setOffset:(CGFloat)offset {
objc_setAssociatedObject(self, &offsetKey, @(offset), OBJC_ASSOCIATION_ASSIGN);
}
- (CGFloat)offset {
NSNumber *numberValue = objc_getAssociatedObject(self, &offsetKey);
return [numberValue intValue];
}
/*
* 对象类型
*/
- (void)setName:(NSString *)name {
objc_setAssociatedObject(self, &nameKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)name {
return objc_getAssociatedObject(self, &nameKey);
}
/*
* 添加结构体属性
* 需要包装成NSValue
*/
- (void)setPoint:(CGPoint)point {
NSValue *value = [NSValue value:&point withObjCType:@encode(CGPoint)];
objc_setAssociatedObject(self,&pointKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (CGPoint)point {
NSValue *value = objc_getAssociatedObject(self, &pointKey);
if(value) {
CGPoint point;
[value getValue:&point];
return point;
}else {
return CGPointZero;
}
}
@end
