Objective-C in a fast way — Part 2

Onur Hüseyin Çantay
3 min readFeb 8, 2019

Hello again after a break I’m here again and I think that it would be great if we continue with our objective-c journey

Associated Object

What is an associated object an associated object is related objects with keys
okey lets dive in

We are using associated object to attach custom data on objects.
Normally you are able to do this with subclassing objects but not every time we don’t suggest to create an instance so here comes the powerful Objective-C feature called Associated Objects

There are some association functions like;

//Set
Void objc_setAssociatedObject(id Object ,void *key,id value, objc_AssociationPollicy policy);
//Get
Void objc_getAssociatedObject(id Object ,void *key);
//Remove
Void objc_removeAssociatedObject(id Object);

The accessing of associated object is functionality equal as accessing an element of NSDictionary like key value

Note -> use mostly global static variables for these keys so you will block any typo faults.
Ok if we got what it does lets make an example of it

With these approach your code is cleaner and you don’t to step over the code portions to understand what this alert does everything is on one place but be careful with retain cycles 🙂

Things To Remember

  • Associated objects provide a means of linking objects together
  • The memory management semantics of associated objects can be defined to mimic owning or non owning relationships
  • Associated objects should be used only if when another approach is not possible since they can easily introduce hard to find bugs.

What is a Class Object ?

Every Objective-C object instance is a pointer to a blob of memory that’s why you see the * next to the type declaring a variable

NSString *someString = @“Some String”;

If you tried to allocate memory for an object on the stack instead you would receive an error from the compiler like;

NSString someVariable = @“Some Variable Value”;
//error: interface variable cannot be statically allocated

There is an another approach to declare objects and that is with;

id someGenericValue = @“This is an Generic String”;

But here we have a little issue like if we try to get a function that NSString doesn’t have the compiler can’t warn us because its generic type variable so it’s better to declare variables with their own type

  • The class hierarchy is modeled trough Class object that each instance has a pointer to ignorer to define its type
  • Introspection should be used when the type of the object cannot be known for certain at compile time
  • Always prefer introspection methods where possible, rather than direct comparison of class objects, since the object may implement message forwarding.

Didn’t you read Part-1 ?
https://medium.com/@ohc3807/objective-c-in-a-fast-way-part-1-f0ad41bab602

References

  1. Matt Galloway — Effective Objective-C 2.0 52 Specific Ways to Improve Your iOS and OS X Programs (2013, Addison Wesley)

--

--