一、类别(运行时完成添加)
.h文件
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (Person)
@property (nonatomic, copy) NSString *name;
@end
NS_ASSUME_NONNULL_END
.m文件
#import "NSObject+Person.h"
#import <objc/runtime.h>
static NSString *nameKey = @"nameKey"; // name的key
@implementation NSObject (Person)
/**
setter方法 getter方法
*/
- (void)setName:(NSString *)name {
objc_setAssociatedObject(self, &nameKey, name, OBJC_ASSOCIATION_COPY);
}
- (NSString *)name {
return objc_getAssociatedObject(self, &nameKey);
}
@end
其他地方调用
- (void)viewDidLoad {
[super viewDidLoad];
NSObject *objc = [[NSObject alloc] init];
objc.name = @"wangwang";
NSLog(@"%@", objc.name);
// Do any additional setup after loading the view.
}
二、类拓展(编译时完成添加)
.h文件不做任何修改,只在.m文件修改,添加需要拓展的私有方法、成员变量,属性
#import "Person.h"
@interface Person(){
NSString *_age;
}
-(void)getUserInfo;
@end
@implementation Person
-(void)getUserInfo{
NSLog(@"====getuserinfo");
}
@end
网友评论