Skip to content

Instantly share code, notes, and snippets.

@kostiakoval
Last active August 29, 2015 13:57
Show Gist options
  • Save kostiakoval/9857097 to your computer and use it in GitHub Desktop.
Save kostiakoval/9857097 to your computer and use it in GitHub Desktop.
Associated object. Associated-NSNumber.m and Associated.m are code snippets for creating methods for property with associated object. KKNSObject+Associated.h is a macro that can be use to automatically create associated methods for property.
- (<#type#>)<#propertyName#> {
return [objc_getAssociatedObject(self, _cmd) <#NSNumberMethod#>];
}
- (void)set<#propertyName#>:(<#type#>)object
{
objc_setAssociatedObject(self, @selector(<#propertyName#>), [NSNumber numberWith:object], OBJC_ASSOCIATION_);
}
- (<#type#>)<#propertyName#> {
return objc_getAssociatedObject(self, _cmd);
}
- (void)set<#propertyName#>:(<#type#>)object
{
objc_setAssociatedObject(self, @selector(<#propertyName#>), object, OBJC_ASSOCIATION_);
}
//
// NSObject+Assosiated.h
// NSObject-Associated
//
// Created by Konstantin Koval on 29/03/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (AssociatedTest)
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) id delegate;
@end
// Implementation
#import "KKNSObject+Associated.h"
@implementation NSObject (AssociatedTest)
ASSOCIATED(name, setName, NSString *, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
ASSOCIATED(delegate, setDelegate, id, OBJC_ASSOCIATION_ASSIGN)
@end
//
// KKNSObject+Assosiated.h
// NSObject-Associated
//
// Created by Konstantin Koval on 29/03/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
/**
* A macro that creates getter and setter for your assosiated object
*
* @param propertyName Getter funtion name
* @param setter Setter funtion name
* @param objc_AssociationPolicy Memory policy for assosiated object
*
* Available option: OBJC_ASSOCIATION_ASSIGN, OBJC_ASSOCIATION_RETAIN_NONATOMIC, OBJC_ASSOCIATION_COPY_NONATOMIC, OBJC_ASSOCIATION_RETAIN, OBJC_ASSOCIATION_COPY
*
*/
#import <objc/runtime.h>
#define ASSOCIATED(propertyName, setter, type, objc_AssociationPolicy)\
- (type)propertyName {\
return objc_getAssociatedObject(self, _cmd);\
}\
\
- (void)setter:(type)object\
{\
objc_setAssociatedObject(self, @selector(propertyName), object, objc_AssociationPolicy);\
}
@zjcdxzy
Copy link

zjcdxzy commented May 2, 2014

great

@vitoziv
Copy link

vitoziv commented Sep 4, 2014

This is cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment