Over a million developers have joined DZone.

iOS Tip: Category Instance Variables

DZone's Guide to

iOS Tip: Category Instance Variables

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

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!

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.


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

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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


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

{{ parent.tldr }}

{{ parent.urlSource.name }}