Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use associated objects in objective-c

Tags:

objective-c

I have recently learned about associated objects in objective-c and how to implement them. From my understanding, they are helpful if you have a property that you want only a single instance of an object to have.

I can't think of any specific use cases for associated objects in objective-c (meaning use cases that I can't do using some other means).

Does anyone have specific examples of when to use associated objects?

like image 826
brenmcnamara Avatar asked Feb 05 '14 22:02

brenmcnamara


People also ask

What is an associated object?

"Associated object" means that you possess an object taken from the desired destination within the last six months, such as a book from a wizard's library, bed linen from a royal suite, or a chunk of marble from a lich's secret tomb.

What is Association in Swift?

object is the source object for the association, actually it is the object that point to the other object. *key is the the key for the association, this can be any void pointer. value is the object you want to store or associate with the source object.

What is Objective-C runtime?

The Objective-C runtime is a runtime library that provides support for the dynamic properties of the Objective-C language, and as such is linked to by all Objective-C apps. Objective-C runtime library support functions are implemented in the shared library found at /usr/lib/libobjc.


1 Answers

It is useful when Apple has designed a class incorrectly, such that you can't subclass it.

A good example is NSURLSessionDownloadTask. Let's suppose that when you create the task you want to attach a piece of data to it, to be retrieved when the final task delegate message arrives.

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    // retrieve data from downloadTask here
}

But you can't subclass NSURLSessionDownloadTask; you have to accept the task that NSURLSession gives you. So you can't attach any data to it by normal means. One solution in this situation is an associated object.

Personally I wish every object behaved like CALayer and CAAnimation, where you can attach as much data to it as you like in the form of key-value pairs, as if the object were secondarily a kind of NSDictionary.

like image 182
matt Avatar answered Jan 03 '23 13:01

matt