Over a million developers have joined DZone.

iOS Tip: Category Instance Variables

· Mobile Zone

Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud, brought to you in partnership with IBM.

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!

The Mobile Zone is brought to you in partnership with Strongloop and IBM.  Visually compose APIs with easy-to-use tooling. Learn how IBM API Connect provides near-universal access to data and services both on-premises and in the cloud.

Topics:

Published at DZone with permission of Alex Curylo, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}