Last active
August 29, 2015 14:10
-
-
Save hirad/6ba3aef5560888cc8f29 to your computer and use it in GitHub Desktop.
Simple Objective-C runtime examples
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
@interface ArchivesEasy : NSObject | |
@end | |
@implementation ArchivesEasy | |
-(id)initWithCoder:(NSCoder *)aDecoder | |
{ | |
if (self = [super init]) { | |
[self enumeratePropertiesWithBlock:^(NSString *key, id value) { | |
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key]; | |
}]; | |
} | |
return self; | |
} | |
-(void)encodeWithCoder:(NSCoder *)aCoder | |
{ | |
[self enumeratePropertiesWithBlock:^(NSString *key, id val) { | |
[aCoder encodeObject:val forKey:key]; | |
}]; | |
} | |
-(void)enumeratePropertiesWithBlock:(void (^)(NSString*, id))block | |
{ | |
unsigned int count; | |
objc_property_t* properties = class_copyPropertyList([self class], &count); | |
for (int i = 0; i < count; i++) { | |
objc_property_t property = properties[i]; | |
NSString* propertyKey = [NSString stringWithCString:property_getName(property) | |
encoding:NSUTF8StringEncoding]; | |
id value = [self valueForKey:propertyKey]; | |
block(propertyKey, value); | |
} | |
} | |
@end | |
// mixin | |
BOOL mixin(Class mixer, Class target) { | |
unsigned int count; | |
Method* methods = class_copyMethodList(mixer, &count); | |
BOOL allSucceeded = YES; | |
for (int i = 0; i < count; i++) { | |
Method m = methods[i]; | |
SEL selector = method_getName(m); | |
IMP implementation = method_getImplementation(m); | |
const char* encoding = method_getTypeEncoding(m); | |
allSucceeded = allSucceeded && class_addMethod(target, selector, implementation, encoding); | |
} | |
return allSucceeded; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment