iOS 分类添加属性
生活随笔
收集整理的這篇文章主要介紹了
iOS 分类添加属性
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.首先在分類文件中導入頭文件?
#import?<objc/runtime.h>
2.實現(xiàn)代碼如下:
(1).h定義文件
#import <UIKit/UIKit.h>@interface UIView (Category)/** 基本數(shù)據(jù)類型*/ @property (nonatomic,assign) CGFloat offset;/** 對象類型*/ @property (nonatomic,copy) NSString *name;/** 結構體(CGPoint)*/ @property (nonatomic,assign) CGPoint point;@end?
(2).m實現(xiàn)文件
#import "UIView+Category.h" #import <objc/runtime.h>static NSString *offsetKey = @"offset"; static NSString *nameKey = @"name"; static NSString *pointKey = @"pointKey";@implementation UIView (Category)/** 添加基本數(shù)據(jù)類型需要轉化為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
?
?
轉載于:https://www.cnblogs.com/HZChenCheng/p/6892806.html
總結
以上是生活随笔為你收集整理的iOS 分类添加属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在Eclipse中使用JUnit4进行单
- 下一篇: 【BZOJ3242】【UOJ#126】【