首先看一下此方法接收的参数
1.被关联的对象,下面举的例子中关联到了UIAlertView
第二步:
结束!!!
- objc_setAssociatedObject(id object, const voidvoid *key, id value, objc_AssociationPolicy policy)
1.被关联的对象,下面举的例子中关联到了UIAlertView
2.要关联的对象的键值,一般设置成静态的,用于获取关联对象的值
3.要关联的对象的值,从接口中可以看到接收的id类型,所以能关联任何对象
4.关联时采用的协议,有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);
- }
- }