天天看點

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      

轉載于:https://www.cnblogs.com/shaoqizhi/p/10416963.html

繼續閱讀