Skip to content

Instantly share code, notes, and snippets.

@srm
Created August 12, 2012 19:05
Show Gist options
  • Save srm/3333794 to your computer and use it in GitHub Desktop.
Save srm/3333794 to your computer and use it in GitHub Desktop.
Storing data in Categories
#import "FLOCow.h"
@interface FLOCow (isMilkable)
- (BOOL) milkable;
- (void) setMilkable:(BOOL)canMilk;
@end
FLOCow+isMilkable
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "FLOCow+isMilkable.h"
@implementation FLOCow (isMilkable)
static char const _milkableKey;
- (BOOL) milkable{
return [objc_getAssociatedObject(self, &_milkableKey) boolValue];
}
- (void) setMilkable:(BOOL)canMilk{
objc_setAssociatedObject (self, &_milkableKey, [NSNumber numberWithBool:canMilk], OBJC_ASSOCIATION_RETAIN);
}
@end
#import <Foundation/Foundation.h>
@interface FLOCow : NSObject
- (NSString *) moo;
@end
#import "FLOCow.h"
@implementation FLOCow
- (NSString *) moo{
return @"Moo!";
}
- (NSString *) description{
return [NSString stringWithFormat:@"I am a %@",[self className]];
}
@end
#import "FLOCow.h"
@interface FLOCow (isMilkable)
- (BOOL) milkable;
- (void) setMilkable:(BOOL)canMilk;
@end
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "FLOCow+isMilkable.h"
@implementation FLOCow (isMilkable)
static char const _milkableKey;
- (BOOL) milkable{
return [objc_getAssociatedObject(self, &_milkableKey) boolValue];
}
- (void) setMilkable:(BOOL)canMilk{
objc_setAssociatedObject (self, &_milkableKey, [NSNumber numberWithBool:canMilk], OBJC_ASSOCIATION_RETAIN);
}
@end
#import <Foundation/Foundation.h>
#import "FLOCow.h"
#import "FLOCow+isMilkable.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
FLOCow * betsy = [[FLOCow alloc] init];
FLOCow * stan = [[FLOCow alloc] init];
NSLog(@"%@", betsy);
NSLog(@"%@", [betsy moo]);
[betsy setMilkable:YES];
[stan setMilkable:NO];
NSLog(@"Is stan milkable? %@", ([stan milkable] ? @"Yes, it's milkable." : @"No, that's silly."));
NSLog(@"Is betsy milkable? %@", ([betsy milkable] ? @"Yes, it's milkable." : @"No, that's silly."));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment