instance variables may not be placed in categories

Avoid Properties in Categories

Objective-C分类中是不允许增加成员变量的(Instance variables may not be placed in categories),我们可以通过运行时函数objc_setAssociatedObject 和 objc_getAssociatedObject 来让分类支持保存和获取一些数据,从而支持属性。

//EOCPerson+FriendShip.h
@interface EOCPerson (FriendShip)
@property (nonatomic, strong) NSArray *friends;
@end

//EOCPerson+FriendShip.m
static const char* kFriendsPropertyKey = "kFriendsPropertyKey";
@implementation EOCPerson (Friendship)
- (NSArray*)friends {
    return objc_getAssociatedObject(self, kFriendsPropertyKey);
}

- (void)setFriends:(NSArray*)friends {
    objc_setAssociatedObject(self, kFriendsPropertyKey, friends, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
原文地址:https://www.cnblogs.com/qiyer/p/5076109.html