1.創(chuàng)建Person類
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy)NSString *name; // 名稱
@end
2.創(chuàng)建Person的類別
#import "Person.h"
@interface Person (addProperty)
// 添加屬性
@property (nonatomic, assign)NSInteger age;
@property (nonatomic, copy)NSString *stu;
@end
3.Person類別.m的實(shí)現(xiàn)
#import "Person+addProperty.h"
#import <objc/runtime.h>
@implementation Person (addProperty)
static char ageKey = 'n';
static char stuKey = 's';
// 給age屬性提供setter和getter方法
- (void)setAge:(NSInteger)age {
NSString *s = [NSString stringWithFormat:@"%ld",(long)age];
objc_setAssociatedObject(self, &ageKey, s, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSInteger)age {
return [objc_getAssociatedObject(self, &ageKey) integerValue];
}
// 給stu屬性提供setter和getter方法
- (void)setStu:(NSString *)stu {
objc_setAssociatedObject(self, &stuKey, stu, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)stu {
return objc_getAssociatedObject(self, &stuKey);
}
4.屬性的使用
#import "ViewController.h"
#import "Person+addProperty.h"
- (void)viewDidLoad {
[super viewDidLoad];
// 測(cè)試分類的添加屬性
Person *p = [[Person alloc] init];
p.name = @"張三"; // 原有的屬性
p.age = 30; // 添加的屬性
p.stu = @"Good"; // 添加的屬性
NSLog(@"%@---%ld---%@",p.name,p.age,p.stu);
}
// 控制臺(tái)打印結(jié)果為
text1[14973:2226652] 張三---30---Good