iOS中的UIAlertView中的关联对象

时间:2017-02-21 03:44:35

标签: ios objective-c runtime objective-c-runtime

关联对象用于在iOS中创建属性以及在iOS中进行一些狡猾的更改。有人会关心解释这是怎么做的吗?

- (IBAction)doSomething:(id)sender {
  UIAlertView *alert = [[UIAlertView alloc]
                        initWithTitle:@"Alert" message:nil
                        delegate:self
                        cancelButtonTitle:@"OK"
                        otherButtonTitles:nil];
  objc_setAssociatedObject(alert, &kRepresentedObject, 
                           sender,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  [alert show];
  
}

- (void)alertView:(UIAlertView *)alertView 
clickedButtonAtIndex:(NSInteger)buttonIndex {
  UIButton *sender = objc_getAssociatedObject(alertView, 
                                              &kRepresentedObject);
  self.buttonLabel.text = [[sender titleLabel] text];
}

苹果的定义也无助于我理解。 “使用给定的密钥和关联策略为给定对象设置关联值。”

1 个答案:

答案 0 :(得分:0)

据我所知,您可以在运行时在现有的类对象中添加新属性。它允许对象在运行时关联键的任意值。

  

关联对象或关联引用,就像它们最初一样   已知 - 是OS X中引入的Objective-C 2.0运行时的一个特性   Snow Leopard(iOS 4中提供)。该术语指的是以下内容   声明了三个C函数,允许对象   在运行时关联键的任意值:

  • objc_setAssociatedObject
  • objc_getAssociatedObject
  • objc_removeAssociatedObjects

为什么我们使用它?因为它允许我们向现有类添加自定义属性,并且可以利用它所需的位置,之后我们将在运行时删除该属性。

根据您在此处的使用情况,您可以说UIAlertView课程中没有发件人属性,并且您无权通过使用<更改UIAlertView strong> associateObject 您可以在警报委托调用时添加所需的运行时属性。

objc_setAssociatedObject(alert, &kRepresentedObject, 
                           sender,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);

这将添加运行时,我们也可以在运行时使用它后删除它。

您可以在此链接中找到更多详细信息: AssociatedObject

希望这有助于在运行时理解 AssociatedObject 概念。