-
-
Save TheNiks/2841349 to your computer and use it in GitHub Desktop.
An example of using @dynamic properties in Objective-C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface Book : NSObject | |
{ | |
NSMutableDictionary *data; | |
} | |
@property (retain) NSString *title; | |
@property (retain) NSString *author; | |
@end | |
@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]; | |
} | |
} | |
@end | |
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], [book.author UTF8String]); | |
book.title = @"1984"; | |
book.author = @"George Orwell"; | |
printf("%s is written by %s\n", [book.title UTF8String], [book.author UTF8String]); | |
[book release]; | |
[pool release]; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment