Question

Is it correct to use objc_setAssociatedObject for class object?

We often simulate class variables using static variables like that: Objective C Static Class Level variables but, can we use Associated objects as alternative?

objc_setAssociatedObject([self class], &STRING_KEY, myString, OBJC_ASSOCIATION_RETAIN);
Was it helpful?

Solution

Yes, a class object is a full-fledged object, so you can do anything to it that you can do with a regular object.

However, it is clearer and simpler to use a global variable.

p.s. Associating it with [self class] is not the same as using a global variable, because [self class] gives you the actual class of the current object, which may vary as this method is inherited by subclasses. Whereas with a global variable it would always be the same variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top