Skip to content

Instantly share code, notes, and snippets.

@kostiakoval
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save kostiakoval/9857097 to your computer and use it in GitHub Desktop.

Select an option

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

zjcdxzy commented May 2, 2014

Copy link
Copy Markdown

great

@vitoziv

vitoziv commented Sep 4, 2014

Copy link
Copy Markdown

This is cool

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