iOS 扩展机制category与associative
来源:互联网 发布:苹果电脑mac使用技巧 编辑:程序博客网 时间:2024/06/01 08:28
下面稍微解说一下这两个扩展机制:
category和associative作为objective-c 扩展机制的两个特性,category可以通过它来扩展方法;associative可以通过它来扩展属性。
在iOS开发过程中,前者category比较常见,也比较简单,这里就不说了,这里主要说一下associative;
后者associative相对用的就比较少,要用associative就必须使用#import<objc/runtime.h>,然后调用objc_setAssociatedObject 和 objc_getAssociatedObject 方法分别为属性添加setter 和 getter方法,就可以实现属性扩展了。
下面介绍一下这两个方法:
①:void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
其中的参数分别是:
Parameters
object: The source object for the association.
key: The key for the association.
value: The value to associate with the key key for object. Pass nil to clear an existing association.
policy: The policy for the association
其中的policy有enum {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
};
②:id objc_getAssociatedObject(id object, void *key)
Parameters
object: The source object for the association.
key: The key for the association.
Return Value
The value associated with the key key for object.
我这里是扩展UIImageview为其添加一个方法和一个属性。
category的头文件:
#import <UIKit/UIKit.h> @interface UIImageView (associate) @property(nonatomic,strong)NSString* myString; -(void)Output; @end
category的实现文件:
#import <objc/runtime.h> #import "UIImageView+associate.h" static void * MyKey = (void *)@"MyKey"; @implementation UIImageView (associate) -(NSString*)myString { return objc_getAssociatedObject(self, MyKey); } -(void)setMyString:(NSString *)string { objc_setAssociatedObject(self, MyKey, string, OBJC_ASSOCIATION_COPY_NONATOMIC); } -(void)Output { NSLog(@"output mystring:%@",self.myString); } @end
说明:头文件中添加了一个属性和一个方法,在实现文件中使用associative特性为属性重写了setter和getter方法,都比较简单。
测试一下:
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Icon@2x.png"]]; imageView.bounds = CGRectMake(50, 50, 100, 100); imageView.myString = @"hello world"; [self.view addSubview:imageView]; [imageView Output];
运行后,模拟器上就显示一个图片,终端输出:output mystring:hello world
- iOS 扩展机制category与associative
- iOS 扩展机制category与associative
- iOS 扩展机制category与associative
- iOS 扩展机制category与associative
- iOS扩展机制category与associative理解
- iOS 扩展机制category与associative
- iOS 扩展机制category与associative
- iOS 扩展机制category与associative
- iOS 扩展机制category与associative
- 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- iOS学习系列 - 扩展机制category与associative
- ldp如下配置不工作
- 避免重复的ajax请求
- Linux下jdk的安装
- 史玉柱亲笔写的脑白金策划方案
- C++中传统枚举和强类型枚举的区别?
- iOS 扩展机制category与associative
- 机器学习系列(4)_机器学习算法一览,应用建议与解决思路
- Mysql主从复制
- StateListDrawable资源
- Android APK反编译获取资源
- 集团性企业数据信息系统解决方案
- C语言BT软件项目总结
- CPC客户端报错 error
- Python之数据规整化:清理、转换、合并、重塑