关联对象

1. 方法

  • 通过一个key和协议关联对象和值
func objc_setAssociatedObject(_ object: Any, _ key: UnsafeRawPointer, _ value: Any?, _ policy: objc_AssociationPolicy)
  • 通过对象和key获取关联
func objc_getAssociatedObject(_ object: Any, _ key: UnsafeRawPointer) -> Any?
  • 移除所有关联
func objc_removeAssociatedObjects(_ object: Any)

2. objc_AssociationPolicy类型

case OBJC_ASSOCIATION_ASSIGN

一个弱引用给对象,类似assign标签

case OBJC_ASSOCIATION_COPY

自动复制关联,类似copy标签

case OBJC_ASSOCIATION_COPY_NONATOMIC

关联对象为copy标签,但是关联过程不是原子的,相当于@property(copy, nonatomic)

case OBJC_ASSOCIATION_RETAIN

自动关联对象为strong标签

case OBJC_ASSOCIATION_RETAIN_NONATOMIC

关联对象为strong标签,但是关联过程不是原子的,相当于@property(strong, nonatomic)

例子

#import <objc/runtime.h>

static void *EOCMyAlertViewKey = "EOCMyAlertViewKey";//自定义key值

- (void)askUserAQuestion {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Question"
                                                    message:@"What do you want to do?"
                                                   delegate:self
                                          cancelButtonTitle:@"Cancel"
                                          otherButtonTitles:@"Continue", nil];
    
    void (^block)(NSInteger) = ^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [self doCancel];
        } else {
            [self doContinue];
        }
    };
    
    objc_setAssociatedObject(alert, EOCMyAlertViewKey, block, OBJC_ASSOCIATION_COPY);//使用copy,把block从栈复制到堆里,保证本程序块结束block可用。
    
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    void (^block)(NSInteger) = objc_getAssociatedObject(alertView, EOCMyAlertViewKey);
    block(buttonIndex);
}

推荐阅读更多精彩内容