ios用category添加属性

来源:互联网 发布:双点伪高斯平滑算法 编辑:程序博客网 时间:2024/04/29 20:54

转载自简书,原文链接: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
  1. 编写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
  1. 访问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
  1. 编写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
  1. 访问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/。

0 0