Skip to content

@mdippery /book.m

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
An example of using @dynamic properties in Objective-C
#import <Foundation/Foundation.h>
@interface Book : NSObject
NSMutableDictionary *data;
@property (retain) NSString *title;
@property (retain) NSString *author;
@implementation Book
@dynamic title, author;
- (id)init
if ((self = [super init])) {
data = [[NSMutableDictionary alloc] init];
[data setObject:@"Tom Sawyer" forKey:@"title"];
[data setObject:@"Mark Twain" forKey:@"author"];
return self;
- (void)dealloc
[data release];
[super dealloc];
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
NSString *sel = NSStringFromSelector(selector);
if ([sel rangeOfString:@"set"].location == 0) {
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
} else {
return [NSMethodSignature signatureWithObjCTypes:"@@:"];
- (void)forwardInvocation:(NSInvocation *)invocation
NSString *key = NSStringFromSelector([invocation selector]);
if ([key rangeOfString:@"set"].location == 0) {
key = [[key substringWithRange:NSMakeRange(3, [key length]-4)] lowercaseString];
NSString *obj;
[invocation getArgument:&obj atIndex:2];
[data setObject:obj forKey:key];
} else {
NSString *obj = [data objectForKey:key];
[invocation setReturnValue:&obj];
int main(int argc, char **argv)
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Book *book = [[Book alloc] init];
printf("%s is written by %s\n", [book.title UTF8String], [ UTF8String]);
book.title = @"1984"; = @"George Orwell";
printf("%s is written by %s\n", [book.title UTF8String], [ UTF8String]);
[book release];
[pool release];
return 0;

Good gist.

Its DNA has been used to provide dynamic cached property support in a Dubrovnik, an Obj-C -> Mono (.NET) bridge and code generator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.