Associated objects are a powerful feature in Objective-C that allow developers to add custom properties to existing classes without subclassing. This capability is particularly useful when working with classes you don't own or can't modify directly.
In Objective-C, associated objects provide a way to dynamically add storage to existing classes at runtime. This feature is part of the Objective-C runtime and is often used in categories to add properties that weren't originally defined in the class.
To work with associated objects, you'll primarily use three functions from the Objective-C runtime:
// Setting an associated object
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
// Getting an associated object
id objc_getAssociatedObject(id object, const void *key);
// Removing all associated objects
objc_removeAssociatedObjects(id object);
Associated objects are frequently used in the following scenarios:
Here's an example of how to use associated objects to add a custom property to a category:
#import <objc/runtime.h>
@interface NSObject (CustomProperty)
@property (nonatomic, strong) NSString *customProperty;
@end
@implementation NSObject (CustomProperty)
- (NSString *)customProperty {
return objc_getAssociatedObject(self, @selector(customProperty));
}
- (void)setCustomProperty:(NSString *)customProperty {
objc_setAssociatedObject(self, @selector(customProperty), customProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
To fully understand and utilize associated objects, it's helpful to be familiar with these related Objective-C concepts:
Associated objects provide a powerful way to extend existing classes in Objective-C. While they should be used thoughtfully, they offer flexibility in scenarios where subclassing or modifying original class definitions isn't possible or practical.