「已注销」
2016-03-07 09:52
采纳率: 66.7%
浏览 1.5k

基于oc的ios开发,如何给一个系统类添加一个属性?

基于oc的ios开发,如何给一个系统类添加一个属性? 目前我知道可以用继承或类别实现。但不知道哪种方式好

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • tongwei1987 2016-03-08 12:03
    已采纳

    用类别:
    .h文件
    #import

    @interface UIButton (TLButton)
    @property(nonatomic,strong,readwrite)NSNumber* cityId;
    @property(nonatomic,strong,readwrite)NSNumber* typeId;
    @property(nonatomic,readwrite)NSNumber* pross;
    @end
    .m文件
    #import "UIButton+TLButton.h"
    @implementation UIButton (TLButton)
    -(NSNumber *)cityId
    {
    return objc_getAssociatedObject(self, @selector(cityId));
    }

    • (void)setCityId:(NSNumber *)cityId
      {

      [self willChangeValueForKey:@"cityId"];
      objc_setAssociatedObject(self, @selector(cityId), cityId, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
      [self didChangeValueForKey:@"cityId"];
      }
      -(NSNumber )typeId
      {
      return objc_getAssociatedObject(self, @selector(typeId));
      }
      -(void)setTypeId:(NSNumber *)typeId
      {
      [self willChangeValueForKey:@"typeId"];
      objc_setAssociatedObject(self, @selector(typeId), typeId, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
      [self didChangeValueForKey:@"typeId"];
      }
      -(NSNumber
      )pross
      {
      return objc_getAssociatedObject(self, @selector(pross));
      }
      -(void)setPross:(NSNumber*)pross
      {
      [self willChangeValueForKey:@"pross"];
      objc_setAssociatedObject(self, @selector(pross), pross, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
      [self didChangeValueForKey:@"pross"];
      }
      @end

    已采纳该答案
    打赏 评论
  • devmiao 2016-03-07 15:14
    打赏 评论
  • llhub 2016-03-10 05:43

    楼上正解,重写getter setter 方法。

    打赏 评论

相关推荐 更多相似问题