Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

iOS Tip: Category Instance Variables

DZone's Guide to

iOS Tip: Category Instance Variables

· Mobile Zone ·
Free Resource
Had you noticed that in recent runtimes every Cocoa object — no, seriously, every Cocoa object — can have arbitrary key/value data associated with it? No, we had not noticed that either. A particularly useful application of that, which no doubt you’ve wished for many times,

 

Faking instance variables in Objective-C categories with Associative References

In OS X 10.6 and iOS 3.1, Apple added Associative References to the Objective-C runtime. Essentially, this means that each and every object has an optional dictionary you can add arbitrary key/value pairs to.

This is a great feature, especially considering that Objective-C has forever had a feature to add methods to existing classes: categories. Categories, however, do not permit you to add instance variables. Using associative references, it’s easy to fake ivars.


Yep, it’s as simple as making your @dynamic implementation of the category’s declared @property wrap a couple C functions. Now that is something we will definitely be using in future!

h/t: @olebegemann!

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}