Skip to content

Instantly share code, notes, and snippets.

@hirad
Last active October 16, 2015 21:22
Show Gist options
  • Save hirad/67ec035889a615ecf021 to your computer and use it in GitHub Desktop.
Save hirad/67ec035889a615ecf021 to your computer and use it in GitHub Desktop.
Fooling around with the ObjC Runtime
@interface ArchivesEasy: NSObject <NSCoding>
@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];
NSLog(@"Encoded value %@ for key %@", val, 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
// Put this in +load of a target class.
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