2019独角兽企业重金招聘Python工程师标准>>>
// XXTest.h
#import <Foundation/Foundation.h>@interface XXTest : NSObject@end@interface XXTest (test)@property (nonatomic, copy) NSString *name;@end// XXTest.m
#import "XXTest.h"
#import <objc/runtime.h>@implementation XXTest@end@implementation XXTest (test)
@dynamic name;char XXName;
- (NSString *)isName {return objc_getAssociatedObject(self, &XXName);
}- (void)setName:(NSString *)name {objc_setAssociatedObject(self, &XXName, name, OBJC_ASSOCIATION_COPY);
}@end
Category 能被用来声明实例或者类方法,但是通常不适合用来声明额外的属性。在Category中声明属性是有效的语法,但是不能声明额外的实例变量。这意味着编译器不会合成任何实例变量,也不会合成任何属性访问器方法。你可以编写自己的访问器方法的类的实现,但你无法跟踪的属性值,除非它已经由原来的存储类。
原文:
Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.
apple 官方文档