ios扩展机制objc_setAssociatedObject,objc_getAssociatedObject

韶镜
2023-12-01

使用例子:

首先导入头文件:#import <objc/runtime.h>

设置静态常量:static char alertinfokey;

- (IBAction)showAlertAction:(id)sender {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title" message:@"warn" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];

    objc_setAssociatedObject(alert, &alertinfokey, @"test value", OBJC_ASSOCIATION_RETAIN);

    [alert show];

    [alert release];

}

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

    if (buttonIndex == 0) {

        NSLog(@"== : %@",objc_getAssociatedObject(alertView, &alertinfokey));

    }

}

输出结果: == : test value
 类似资料: