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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-02
  • 2022-12-23
猜你喜欢
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
  • 2021-11-19
  • 2021-09-09
  • 2022-12-23
  • 2021-07-13
相关资源
相似解决方案