ios用category添加属性
来源:互联网 发布:双点伪高斯平滑算法 编辑:程序博客网 时间:2024/04/29 20:54
转载自简书,原文链接:http://www.jianshu.com/p/00f84e05be49,感谢
首先说明一下,直接在Category中是不能添加属性的,就算在.m文件中实现了相应的getter和setter方法,调用的时候也是会报错的。
首先看下报错情况
Category添加字段(常规方法)
- 编写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
- 编写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
- 访问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方法)
- 编写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
- 编写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
- 访问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
- ios用category添加属性
- iOS 用宏在category里给对象添加属性
- iOS 用宏在category里给对象添加属性
- category 给IOS原生类添加属性
- IOS下Category添加属性字段
- IOS通过runtime给category添加属性
- iOS (Category)runtime动态添加属性
- iOS下Category添加属性字段
- iOS中OC给Category添加属性
- 用Category给类中添加属性
- 给Category添加属性
- Category添加属性
- category添加属性
- category动态添加属性
- Category添加属性字段
- Category 动态添加属性
- iOS 给category添加属性的小技巧
- iOS开发之category动态添加属性的方法------关联
- 分布式服务框架的4项特性
- git之创建与合并分支
- SQL Server 自定义函数
- UINavigationController 导航控制器 IOS7适配 导航栏不透明
- python MySQLdb在windows及Linux环境下的快速安装
- ios用category添加属性
- Linux概念架构的理解
- PHP 常用函数积累
- print_r、var_dump、var_export
- cJSON学习
- Forward a TCP port to another IP or port using NAT with Iptables
- web.py源码分析: application
- 第1章第1节练习题1 删除最小值
- Android 内存分析工具MAT(下)