Objective-C Associated Objects

Download ios eBook

Introduction

First introduced in iOS 3.1 as part of the Objective-C runtime, associated objects provide a way to add instance variables to an existing class object (w\o subclassing.

This means you'll be able to attach any object to any other object without subclassing.

Syntax

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

  • id objc_getAssociatedObject(id object, void *key)

  • void objc_removeAssociatedObjects(id object)

Parameters

ParamDetails
objectThe existing object you want to modify
keyThis can basically be any pointer that has a constant memory address, but a nice practice is to use here a computed property (getter)
valueThe object you want to add
policyThe memory policy for this new value i.e. should it be retained / assigned, copied etc.. just like any other property you'd declare

Remarks

More details here:

NSHipster

@kostiakoval

kingscocoa

Related Examples

Stats

28 Contributors: 1
Wednesday, February 15, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook