iOS下Category添加属性字段

http://www.jianshu.com/p/00f84e05be49

首先说明一下,直接在Category中是不能添加属性的,就算在.m文件中实现了相应的getter和setter方法,调用的时候也是会报错的。

首先看下报错情况

Category添加字段(常规方法)

1, 编写Category头文件,以UIImage为例

//
//  UIImage+category.h
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//
#import <UIKit/UIKit.h>

@interface UIImage (category)

// 在UIImage中新建一个tag属性
@property (nonatomic, copy) NSString *tag;

@end

2,编写Category源文件

//
//  UIImage+category.m
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//

#import "UIImage+category.h"

@implementation UIImage (category)

- (NSString *)tag {
    return self.tag;
}

- (void)setTag:(NSString *)tag {
    self.tag = [tag copy];
}
@end

3, 访问Category添加的tag属性

UIImage *image = [UIImage imageNamed:@""];
[image setTag:@"100"];
NSLog(@"tag:%@", [image tag]);

打印信息为:

2015-08-12 15:17:10.321 InformPub[16828:1373803] CUICatalog: Invalid asset name supplied: 
2015-08-12 15:17:10.321 InformPub[16828:1373803] tag:(null)

看到了没有,我们设置了tag值,完全没有用。那么有没有什么办法可以给Category添加属性字段呢?请看下面:

Category添加字段(Runtime方法)

1,编写Category头文件,还是以UIImage为例

//
//  UIImage+category.h
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//
#import <UIKit/UIKit.h>

@interface UIImage (category)

// 在UIImage中新建一个tag属性
@property (nonatomic, copy) NSString *tag;

@end

2,编写Category源文件

//
//  UIImage+category.m
//  
//
//  Created by Linf on 15-5-19.
//  Copyright (c) 2015年 Linf. All rights reserved.
//

#import "UIImage+category.h"

static const void *tagKey = &tagKey;

@implementation UIImage (category)

- (NSString *)tag {
    return objc_getAssociatedObject(self, tagKey);
}

- (void)setTag:(NSString *)tag {
    objc_setAssociatedObject(self, tagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end

3, 访问Category添加的tag属性

UIImage *image = [UIImage imageNamed:@""];
[image setTag:@"100"];
NSLog(@"tag:%@", [image tag]);

打印信息为:

2015-08-12 14:57:58.777 InformPub[16741:1271788] tag:100

到这里代码就添加完成了,Category就可以添加属性字段了。这里面用到了objective-c的Runtime。如果有不了解Runtime的小伙伴,可以参考以下网站:http://southpeak.github.io/blog/2014/10/25/objective-c-runtime-yun-xing-shi-zhi-lei-yu-dui-xiang/



文/zuolingfeng(简书作者)
原文链接:http://www.jianshu.com/p/00f84e05be49
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值