iOS Objective-C Associated Objects

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any iOS Question?