2 qq 20401801 qq_20401801 于 2016.03.07 17:52 提问

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

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

3个回答

tongwei1987
tongwei1987   2016.03.08 20: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
devmiao   Ds   Rxr 2016.03.07 23:14
llhub
llhub   2016.03.10 13:43

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

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!