runTime动态给类添加属性

#项目中需要给系统类添加属性

#需要注意的地方就是.m中   set 和 get  ,get方法中方法名和添加的属性名一致,set中可以用驼峰

#import <UIKit/UIKit.h>


@interface UITextField (AddProperty)
/** 添加额外标签*/
@property (nonatomic, copy)  NSString* otherTag;
@end
//
//  UITextField+AddProperty.m
//  phone-wisdomFarmland
//
//  Created by apple on 2019/2/19.
//  Copyright © 2019年 apple. All rights reserved.
//

#import "UITextField+AddProperty.h"
#import <objc/runtime.h>

static NSString *targetVaulekey = @"test_otherTagKey";

@implementation UITextField (AddProperty)
@dynamic otherTag;

-(NSString *)otherTag{
    return objc_getAssociatedObject(self, &targetVaulekey);
}

- (void)setOtherTag:(NSString *)otherTag{
    objc_setAssociatedObject(self, &targetVaulekey, otherTag, OBJC_ASSOCIATION_RETAIN);
}

@end

猜你喜欢

转载自www.cnblogs.com/shaoqizhi/p/10416963.html