What is objc_setAssociatedObject() and in what cases should it be used?

后端 未结 4 1166
有刺的猬
有刺的猬 2020-11-28 20:26

In a project I have taken on, the original author has opted to use objc_setAssociatedObject() and I\'m not 100% clear what it does or why they decided to use it

4条回答
  •  天命终不由人
    2020-11-28 21:12

    From the reference documents on Objective-C Runtime Reference:

    You use the Objective-C runtime function objc_setAssociatedObject to make an association between one object and another. The function takes four parameters: the source object, a key, the value, and an association policy constant. The key is a void pointer.

    • The key for each association must be unique. A typical pattern is to use a static variable.
    • The policy specifies whether the associated object is assigned,
      retained, or copied, and whether the
      association is be made atomically or
      non-atomically. This pattern is
      similar to that of the attributes of
      a declared property (see “Property
      Declaration Attributes”). You specify the policy for the relationship using a constant (see
      objc_AssociationPolicy and
      Associative Object Behaviors).

    Establishing an association between an array and a string

    static char overviewKey;
    
    
    
    NSArray *array =
    
        [[NSArray alloc] initWithObjects:@"One", @"Two", @"Three", nil];
    
    // For the purposes of illustration, use initWithFormat: to ensure
    
    // the string can be deallocated
    
    NSString *overview =
    
        [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];
    
    
    
    objc_setAssociatedObject (
    
        array,
    
        &overviewKey,
    
        overview,
    
        OBJC_ASSOCIATION_RETAIN
    
    );
    
    
    
    [overview release];
    
    // (1) overview valid
    
    [array release];
    
    // (2) overview invalid
    

    At point 1, the string overview is still valid because the OBJC_ASSOCIATION_RETAIN policy specifies that the array retains the associated object. When the array is deallocated, however (at point 2), overview is released and so in this case also deallocated. If you try to, for example, log the value of overview, you generate a runtime exception.

提交回复
热议问题