swiftOC语法iOS基础·OC高级篇

OC关联对象之objc_setAssociatedObject的

2017-10-06  本文已影响83人  makemake

对象关联类型

关联类型 等效的@property属性
OBJC_ASSOCIATION_ASSIGN assign
OBJC_ASSOCIATION_RETAIN_NONATOMIC nonatomic,retain
OBJC_ASSOCIATION_COPY_NONATOMIC nonatomic,copy
OBJC_ASSOCIATION_RETAIN retain
OBJC_ASSOCIATION_COPY copy

管理关联对象的方法:
objc_setAssociatedObject(id object, void * key, id value, <objc_AssociationPolicy policy)
以给定的key为对象设置关联对象的value

objc_getAssociatedObject(id _Nonnull object, const void * _Nonnull key)
根据key从对象中获取相应的关联对象的value

objc_removeAssociatedObjects(id _Nonnull object)
移除所有关联对象

使用时通常使用静态的全局变量做key

demo:

  static void *MKEAlterViewKey = "MKEAlterViewKey";

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"123" message:@"345" delegate:self cancelButtonTitle:@"cancels" otherButtonTitles:@"jixu", nil];

    void (^block)(NSInteger) = ^(NSInteger buttonIndex){   };


  //block 为value MKEAlterViewKey为key 与对象alert关联
    objc_setAssociatedObject(alert, MKEAlterViewKey, block, OBJC_ASSOCIATION_COPY);

    [alert show];

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

//获取value
    void (^blcok)(NSInteger) = objc_getAssociatedObject(alertView, MKEAlterViewKey);
    blcok(buttonIndex);

}
上一篇下一篇

猜你喜欢

热点阅读