Effective Objective-C 2.0: Associated Objects

原创 2013年12月03日 14:51:05

例子有点少, 内存管理方面不清楚~~, 


Item 10: Use Associated Objects to Attach Custom Data to Existing Classes

Sometimes, you want to associate information with an object. Normally, you would do this by subclassing the object’s class and use that instead. However, you can’t always do this, since instances of the class might be created for you by some means and you cannot tell it to create instances of your class instead. That’s where the powerful Objective-C feature called Associated Objects comes in handy.

Objects are associated with other objects, using a key to identify them. They are also designated a storage policy to govern memory-management semantics of the stored value. The storage policies are defined by the enumeration objc_AssociationPolicy, which contains the values shown in Table 2.1 against the @propertyattribute for the equivalent if the association were a property (seeItem 6 for further information on properties).

Table 2.1 Object Association Types

Image

Management of associations is performed using the following methods:

Image void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)

Sets up an association of object to value with the given key and policy.

Image id objc_getAssociatedObject(id object, void *key)

Retrieves the value for the association on object with the given key.

Image void objc_removeAssociatedObjects(id object)

Removes all associations against object.

The accessing of associated objects is functionally similar to imagining that the object is an NSDictionary and calling [object setObject:value forKey:key] and [object objectForKey:key]. An important difference to note, though, is that key is treated purely as an opaque pointer. Whereas with a dictionary, keys are regarded equal if they return YES for isEqual:, the key for associated objects must be the exact same pointer for them to matchFor this reason, it is common to use static global variables for the keys.

An Example of Using Associated Objects

In iOS development, it’s common to use the UIAlertView class, which provides a standard view for showing an alert to the user. There’s a delegate protocol to handle when the user taps a button to close it; however, using delegation splits up the code of creation of the alert and handling the tap. This makes it slightly awkward to read, as the code is split between two places. Here is an example of what using a UIAlertView would look like normally:

- (void)askUserAQuestion {
    UIAlertView *alert = [[UIAlertView alloc]
                             initWithTitle:@"Question"
                               message:@"What do you want to do?"
                                 delegate:self
                        cancelButtonTitle:@"Cancel"
                        otherButtonTitles:@"Continue"nil];
      [alert show];
}

// UIAlertViewDelegate protocol method
- (void)alertView:(UIAlertView *)alertView
        clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self doCancel];
    } else {
        [self doContinue];
    }
}

This pattern gets even more complicated if you ever want to present more than one alert in the same class, since you then have to checkthe alertView parameter passed into the delegate method and switch based on that. It would be much simpler if the logic for what to do when each button is tapped could be decided when the alert is created. This is where an associated object can be used. A solution is to set a block against an alert when it is created and then read that block out when the delegate method is run. Implementing it would look like this:

#import <objc/runtime.h>

static void *EOCMyAlertViewKey = "EOCMyAlertViewKey";

- (void)askUserAQuestion {
    UIAlertView *alert = [[UIAlertView alloc]
                             initWithTitle:@"Question"
                               message:@"What do you want to do?"
                                  delegate:self
                        cancelButtonTitle:@"Cancel"
                        otherButtonTitles:@"Continue"nil];

      void (^block)(NSInteger) = ^(NSInteger buttonIndex){
        if (buttonIndex == 0) {
            [self doCancel];
        } else {
            [self doContinue];
        }
    };

      objc_setAssociatedObject(alert,
                               EOCMyAlertViewKey,
                               block,
                               OBJC_ASSOCIATION_COPY);

      [alert show];
}

// UIAlertViewDelegate protocol method
- (void)alertView:(UIAlertView*)alertView
        clickedButtonAtIndex:(NSInteger)buttonIndex
{
    void (^block)(NSInteger) =
        objc_getAssociatedObject(alertView, EOCMyAlertViewKey);
    block(buttonIndex);
}

With this approach, the code for creating the alert and handling the result is all in one place, making it more readable than before, as you don’t have to flick between two portions of code to understand why the alert view is being used. You would, however, need to be careful with this approach, as retain cycles could easily be introduced if the block captured. See Item 40 for more information on this problem.

As you can see, this approach is very powerful, but it should be used only when there’s no other way of achieving what you need to do. Widespread use of this approach could get out of hand very quickly and make debugging difficult. Retain cycles become harder to reason, since there is no formal definition of the relationship between the associated objects, as the memory-management semantics are defined at association time rather than in an interface definition. So proceed with caution when using this approach, and do not use it purely because you can. An alternative way of achieving the same with UIAlertView would be to subclass it and add a property to store the block. I would suggest this approach over associated objects if thealert view were to be used more than once.

Things to Remember

Image Associated objects provide a means of linking two objects together.

Image The memory-management semantics of associated objects can be defined to mimic owning or nonowning relationships.

Image Associated objects should be used only when another approach is not possible, since they can easily introduce hard-to-find bugs.

相关文章推荐

深入学习Objective-C(二)理解 objc 关联对象 (Associated Objects)

我们都知道,我们在普通的 objc 类中,一般我们都会把成员变量声明在@interface中,如果你想把成员变量暴露在头文件中,你可以把它声明在实现文件中,甚至你也可以放在类扩展的区域中,但是,你却不...
  • lkeplei
  • lkeplei
  • 2015年03月27日 19:12
  • 451

Objective-C Associated Objects 的实现原理

我们知道,在 Objective-C 中可以通过 Category 给一个现有的类添加属性,但是却不能添加实例变量,这似乎成为了 Objective-C 的一个明显短板。然而值得庆幸的是,我们可以通过...

深入学习Objective-C(二)理解 objc 关联对象 (Associated Objects)

今天看了下 objc 2.0 引入的强大特性:关联对象,下面把我的理解与大家分享一下。 我们都知道,我们在普通的 objc 类中,一般我们都会把成员变量声明在@interface中,如果你想把成...
  • Dev_Ho
  • Dev_Ho
  • 2014年11月03日 23:00
  • 6298

《Effective Objective-C 2.0 编写高质量iOS与OS X代码的52个有效方法》--读书笔记

个人觉得这本书很不错!里面有很多很实用但以前没有太注意的地方,所以想纪录下来,当作自己的读书笔记吧。 熟悉Objective-C 1)Objective-C语言使用“消息结构”而不是“函数调用”。O...

【Effective Objective-C 2.0读书笔记】第四章:协议和分类

Objective-C中的“协议”(protocal)类似于java中的接口。协议最为常见的用途是实现委托模式。不过也有其他用法。 “分类”(category)机制,可以无须继承子类即可直接为当前类...

【Effective Objective-C 2.0读书笔记】第二章:对象、消息、运行期

在Objective-C等面向对象语言中,“对象”是基本构造单元,开发者可以通过对象来存储并传递数据。在对象之间传递数据并执行任务的过程即为“消息传递”。当应用程序运行起来之后,为其提供相关支持的代码...

Effective Objective-C 2.0: Item 43: Know When to Use GCD and When to Use Operation Queues

Item 43: Know When to Use GCD and When to Use Operation Queues GCD is a fantastic technology, but...

Effective Objective-C 2.0: Item 16:Designated Initializer

Item 16: Have a Designated Initializer All objects need to be initialized. When initializing an o...

Effective Objective-C 2.0:Item 25: Always Prefix Category Names on Third-Party Classes

Item 25: Always Prefix Category Names on Third-Party Classes Categories are commonly used to add ...

Effective Objective-C 2.0: Item 41: Prefer Dispatch Queues to Locks for Synchronization

Item 41: Prefer Dispatch Queues to Locks for Synchronization Sometimes in Objective-C, you will com...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Effective Objective-C 2.0: Associated Objects
举报原因:
原因补充:

(最多只允许输入30个字)