zoukankan      html  css  js  c++  java
  • 关联引用(Associative References)为现有类添加变量

    能够模拟添加一个实例变量到一个已有的类中,能够添加存储到一个对象中而不需要改变类的定义。

    1.通过分类给已有类添加属性

    1  @interface Person:NSObject
    2  @end
    3 
    4  @implementation Person
    5  @end
     1 @interface Person(EmailAddress)
     2 @property (nonatomic,readwrite,copy)NSString *emailAddress;
     3 @end
     4 
     5 @implement Person(EmailAddress)
     6 
     7 static char emailAddressKey;
     8 
     9 -(NSString*)emailAddress{
    10     return obj_getAssociatedObject(self,&emailAddressKey);//取出关联引用
    11 }
    12 
    13 -(void)setEmailAddress:(NSString*)emailAddress{
    14     objc_setAssociatedObject(self,&emailAddressKey,emailAddress,OBJC_ASSOCIATION_COPY);//设置关联引用
    15 }
    16 
    17 @end

    2.利用关联引用,给UIAlertView添加一个变量。

     1 static char kRepresentedObject;
     2 
     3 NSString *addThing = "添加的东西";
     4 UIAlertView *alert = [UIAlertView alloc]initWithTitile:@"Alert" message:nil delegate:self cancelButtonTitle:@"ok" otherButtonTitle:nil];
     5 
     6 obj_setAssociatedObject(alert,&kRepresentedObject,addThing,OBJC_ASSOCIATION_RETAIN_NONATOMIC);//将addThing添加到alert
     7 
     8 [alert show];
     9 
    10 
    11 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    12     NSString *addThing = objc_getAssociatedObject(alertView,&kRepresentedObject);  //取出
    13 }
  • 相关阅读:
    wpf-x-指令元素
    意法半导体STM32单片机特性
    非易失性存储器MRAM的两大优点
    静态SDRAM和动态SDRAM的区别
    使用SRAM如何节省芯片面积
    不同类别存储器基本原理
    串口SRAM和并口SRAM的引脚区别
    SRAM存储器芯片地址引脚线短路检测方法
    2020年国内MCU市场有望突破500亿元
    MRAM可以替代NOR或SRAM
  • 原文地址:https://www.cnblogs.com/cokecoffe/p/3021763.html
Copyright © 2011-2022 走看看