iOS中关联对象的简单使用objc_setAssociatedObject
来源:互联网 发布:分布式数据库设计 编辑:程序博客网 时间:2024/05/22 03:16
首先看一下此方法接收的参数
设置
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
获取
id objc_getAssociatedObject(id object, const void *key)
被关联的对象,下面举的例子中关联到了UIAlertView
- 要关联的对象的键值,一般设置成静态的,用于获取关联对象的值
- 要关联的对象的值,从接口中可以看到接收的id类型,所以能关联任何对象
- 关联时采用的协议,有assign,retain,copy等协议,具体可以参考官方文档
下面就以UIAlertView为例子简单介绍一下使用方法
使用场景:在UITableView中点击某一个cell,这时候弹出一个UIAlertView,然后在UIAlertView消失的时候获取此cell的信息,我们就获取cell的indexPath
第一步:
#import <objc/runtime.h>static char kUITableViewIndexKey;- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{......UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"这里是xx楼" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil];//然后这里设定关联,此处把indexPath关联到alert上objc_setAssociatedObject(alert, &kUITableViewIndexKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);[alert show];
}
第二步:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (buttonIndex == 0) { NSIndexPath *indexPath = objc_getAssociatedObject(alertView, &kUITableViewIndexKey); NSLog(@"%@", indexPath); }}
其实,实际上这种设置和获取的方法,就相当于一个全局的字典,用来存取键值对。
0 0
- iOS中关联对象的简单使用(objc_setAssociatedObject)
- iOS中关联对象的简单使用(objc_setAssociatedObject)
- iOS中关联对象的简单使用objc_setAssociatedObject
- iOS中关联对象的简单使用objc_setAssociatedObject
- objc_setAssociatedObject 关联的使用
- IOS中的关联对象实现objc_setAssociatedObject
- objc_setAssociatedObject的简单使用
- iOS关联(objc_setAssociatedObject)
- iOS关联,objc_getAssociatedObject, objc_setAssociatedObject
- 【iOS开发技术】对象关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)
- 【iOS开发技术】对象关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)
- OC对象关联~objc_setAssociatedObject/objc_getAssociatedObject
- iOS-关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)
- iOS 关联对象的使用
- objc_setAssociatedObject与Block的简单使用
- objc_setAssociatedObject与Block的简单使用
- 对象关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)
- [IOS] 关联(objc_setAssociatedObject、objc_getAssociatedObject、objc_removeAssociatedObjects)
- NWERC 2007 / UVa 12124 Assemble (二分搜索&最小值最大问题)
- [Linux 线程]深入理解pthread_cond_wait、pthread_cond_signal
- hive 索引
- CAS—认证原理
- 用matlab处理4/8/n皇后问题
- iOS中关联对象的简单使用objc_setAssociatedObject
- XZ_iOS之iOS禁止程序在后台运行和申请后台3分钟的时长
- Linux使用记录(虚拟机中安装redhat并且安装Oracle数据库)
- Oracle 用户和权限
- 使用IDLE和Python Shell编写python
- Glide图片框架学习
- 几行代码解决RadioGroup+Fragment的重叠问题
- Spring ActiveMQ整合+注解消息监听
- 苹果应用上架,图片的要求(2017年4月27日)