1.基本资料
2.基本概念
把一个value关联到另外一个object里,类似NSDictionary的 setValue:forKey 。
用 objc_setAssociatedObject 关联以后,用 objc_getAssociatedObject 取出使用。
objc_AssociationPolicy 属性 是设定该value在object内的属性,即 assgin, (retain,nonatomic)...等
3.例:
上面例子中,把block关联到 alert里面
//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 void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, const void *key)
void objc_removeAssociatedObjects(id object)
2.基本概念
把一个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];
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();
}
}
上面例子中,把block关联到 alert里面