Skip to content
Browse files

added method for dynamically adding instance methods at runtime

  • Loading branch information...
1 parent f727f7d commit 345b4c55fa28a1d04f941aed75209777a5874937 @odrobnik odrobnik committed Mar 6, 2013
Showing with 31 additions and 0 deletions.
  1. +9 −0 Core/Source/NSObject+DTRuntime.h
  2. +22 −0 Core/Source/NSObject+DTRuntime.m
View
9 Core/Source/NSObject+DTRuntime.h
@@ -23,6 +23,15 @@
*/
- (void)addDeallocBlock:(void(^)())block;
+/**
+ Adds a new instance method to a class. All instances of this class will have this method.
+
+ @param name The name of the method.
+ @param The block to execute for the instance method, a pointer to the instance is passed as the only parameter.
+ @returns `YES` if the operation was successful
+ */
++ (BOOL)addInstanceMethodWithSelectorName:(NSString *)selectorName block:(void(^)(id))block;
+
/**-------------------------------------------------------------------------------------
@name Method Swizzling
---------------------------------------------------------------------------------------
View
22 Core/Source/NSObject+DTRuntime.m
@@ -35,6 +35,28 @@ - (void)addDeallocBlock:(void(^)())block
[deallocBlocks addObject:executor];
}
++ (BOOL)addInstanceMethodWithSelectorName:(NSString *)selectorName block:(void(^)(id))block
+{
+ // don't accept nil name
+ NSParameterAssert(selectorName);
+
+ // don't accept NULL block
+ NSParameterAssert(block);
+
+ // See http://stackoverflow.com/questions/6357663/casting-a-block-to-a-void-for-dynamic-class-method-resolution
+
+#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_7
+ void *impBlockForIMP = (void *)objc_unretainedPointer(block);
+#else
+ id impBlockForIMP = (__bridge id)objc_unretainedPointer(block);
+#endif
+
+ IMP myIMP = imp_implementationWithBlock(impBlockForIMP);
+
+ SEL selector = NSSelectorFromString(selectorName);
+ return class_addMethod([self class], selector, myIMP, "v@:");
+}
+
#pragma mark - Method Swizzling
+ (void)swizzleMethod:(SEL)selector withMethod:(SEL)otherSelector

0 comments on commit 345b4c5

Please sign in to comment.
Something went wrong with that request. Please try again.