1. 方法
- 通過一個key和協(xié)議關(guān)聯(lián)對象和值
func objc_setAssociatedObject(_ object: Any, _ key: UnsafeRawPointer, _ value: Any?, _ policy: objc_AssociationPolicy)
- 通過對象和key獲取關(guān)聯(lián)
func objc_getAssociatedObject(_ object: Any, _ key: UnsafeRawPointer) -> Any?
- 移除所有關(guān)聯(lián)
func objc_removeAssociatedObjects(_ object: Any)
2. objc_AssociationPolicy類型
一個弱引用給對象,類似assign標簽
自動復(fù)制關(guān)聯(lián),類似copy標簽
case OBJC_ASSOCIATION_COPY_NONATOMIC
關(guān)聯(lián)對象為copy標簽,但是關(guān)聯(lián)過程不是原子的,相當(dāng)于@property(copy, nonatomic)
自動關(guān)聯(lián)對象為strong標簽
case OBJC_ASSOCIATION_RETAIN_NONATOMIC
關(guān)聯(lián)對象為strong標簽,但是關(guān)聯(lián)過程不是原子的,相當(dāng)于@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從棧復(fù)制到堆里,保證本程序塊結(jié)束block可用。
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
void (^block)(NSInteger) = objc_getAssociatedObject(alertView, EOCMyAlertViewKey);
block(buttonIndex);
}