Skip to content

Instantly share code, notes, and snippets.

@CarterA
Created August 8, 2012 23:42
Show Gist options
  • Save CarterA/3299765 to your computer and use it in GitHub Desktop.
Save CarterA/3299765 to your computer and use it in GitHub Desktop.
Objective-C Associated Objects, Subscripting Edition
#import <Foundation/Foundation.h>
#import "NSObject+OP6AssociatedObjects.h"
int main(int argc, char *argv[]) {
NSObject *testObject = [NSObject new];
testObject.associatedObjects[@"pi"] = @(M_PI);
NSLog(@"%@", [testObject.associatedObjects[@"pi"] stringValue]); // Logs 3.141592653589793
return EXIT_SUCCESS;
}
//
// NSObject+OP6AssociatedObjects.h
//
// Created by Carter Allen on 8/8/12.
// Copyright (c) 2012 Opt-6 Products, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (OP6AssociatedObjects)
@property (readonly) NSMutableDictionary *associatedObjects;
@end
//
// NSObject+OP6AssociatedObjects.m
//
// Created by Carter Allen on 8/8/12.
// Copyright (c) 2012 Opt-6 Products, LLC. All rights reserved.
//
#import "NSObject+OP6AssociatedObjects.h"
#import <objc/runtime.h>
const char *OP6AssociatedObjectsDictionaryKey = "OP6AssociatedObjectsDictionaryKey";
@implementation NSObject (OP6AssociatedObjects)
- (NSMutableDictionary *)associatedObjects {
NSMutableDictionary *associatedObjects = objc_getAssociatedObject(self, OP6AssociatedObjectsDictionaryKey);
if (!associatedObjects) {
associatedObjects = [NSMutableDictionary new];
objc_setAssociatedObject(self, OP6AssociatedObjectsDictionaryKey, associatedObjects, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return associatedObjects;
}
@end
//
// NSObject+OP6AssociatedObjects.h
//
// Created by Carter Allen on 8/8/12.
// Copyright (c) 2012 Opt-6 Products, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (OP6AssociatedObjects)
@property (readonly) NSMutableDictionary *associatedObjects;
@end
//
// NSObject+OP6AssociatedObjects.m
//
// Created by Carter Allen on 8/8/12.
// Copyright (c) 2012 Opt-6 Products, LLC. All rights reserved.
//
#import "NSObject+OP6AssociatedObjects.h"
#import <objc/runtime.h>
const char *OP6AssociatedObjectsDictionaryKey = "OP6AssociatedObjectsDictionaryKey";
@implementation NSObject (OP6AssociatedObjects)
- (NSMutableDictionary *)associatedObjects {
NSMutableDictionary *associatedObjects = objc_getAssociatedObject(self, OP6AssociatedObjectsDictionaryKey);
if (!associatedObjects) {
associatedObjects = [NSMutableDictionary new];
objc_setAssociatedObject(self, OP6AssociatedObjectsDictionaryKey, associatedObjects, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return associatedObjects;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment