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