關聯屬性見解

雖然在類擴展中不能添加實例變量,只能添加方法,不過屬性並非實例變量,而是set與get的體現,但是可以通過關聯引用向任何對象添加鍵——值數據,上代碼:

@implementation ViewController

static const char kRepresentedObject;

- (IBAction)doSomething:(id)sender {


  UIAlertView *alert = [[UIAlertView alloc]
                        initWithTitle:@"Alert" message:nil
                        delegate:self
                        cancelButtonTitle:@"OK"
                        otherButtonTitles:nil];
    
  /*
    objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
   
   id object  關聯對象
   const void *key 固定的鍵
   id value 對應的值
   objc_AssociationPolicy policy 關聯策略
   
  */
    
  objc_setAssociatedObject(alert, &kRepresentedObject,
                           sender,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  [alert show];
 
}

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


  UIButton *sender = objc_getAssociatedObject(alertView,
                                              &kRepresentedObject);
    
/*
 id objc_getAssociatedObject(id object, const void *key)
 
 id object  關聯對象
 const void *key 固定鍵對應的地址
 
 */
  self.buttonLabel.text = [[sender titleLabel] text];
}


objc_removeAssociatedObjects 用來移除關聯


總結:關聯應用其實就是將兩個對象相互關聯起來,通過一個固定的鍵和對象對應另一個對象,只要第一個對象還在就可以通過固定鍵的對應地址獲取到第二個對象信息,由此而來可以在不添加變量,不改變類定義,增加類的空間   有時可以達到和不錯的效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章