-
1.基本资料
- //policy
- enum {
- OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */
- OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.
- * The association is not made atomically. */
- OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied.
- * The association is not made atomically. */
- OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object.
- * The association is made atomically. */
- OBJC_ASSOCIATION_COPY = 01403 /**< Specifies that the associated object is copied.
- * The association is made atomically. */
- };
- /// Type to specify the behavior of an association.
- typedef uintptr_t objc_AssociationPolicy;
- //method
- void objc_setAssociatedObject(id object, const voidvoid *key, id value, objc_AssociationPolicy policy)
- id objc_getAssociatedObject(id object, const voidvoid *key)
- void objc_removeAssociatedObjects(id object)
关联的方式
OBJC_ASSOCIATION_ASSIGN 弱引用
OBJC_ASSOCIATION_RETAIN_NONATOMIC
强类型引用并原子安全性
OBJC_ASSOCIATION_COPY_NONATOMIC copy内容并创建新地址
OBJC_ASSOCIATION_RETAIN
OBJC_ASSOCIATION_COPY
2.基本概念
把一个value关联到另外一个object里,类似NSDictionary的 setValue:forKey 。
用 objc_setAssociatedObject 关联以后,用 objc_getAssociatedObject 取出使用。
objc_AssociationPolicy 属性 是设定该value在object内的属性,即 assgin, (retain,nonatomic)...等
把一个value关联到另外一个object里,类似NSDictionary的 setValue:forKey 。
用 objc_setAssociatedObject 关联以后,用 objc_getAssociatedObject 取出使用。
objc_AssociationPolicy 属性 是设定该value在object内的属性,即 assgin, (retain,nonatomic)...等
3.例:
- <pre name="code" class="objc">
- #import <objc/runtime.h>
- -(void)testAlertBlock
- {
- UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"this is a bolck_alert"
- message:@"testtesttest"
- delegate:self
- cancelButtonTitle:@"取消"
- otherButtonTitles:@"确定", nil nil];
- void (^block)()=^{
- NSLog(@"alert pressed sure-button");
- };
- objc_setAssociatedObject(alert, @"Alert_block", block, OBJC_ASSOCIATION_COPY_NONATOMIC);
- [alert show];
- }
- - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
- {
- void (^block)()=objc_getAssociatedObject(alertView, @"Alert_block");
- if (block) {
- block();
- }
- }