Skip to content

Instantly share code, notes, and snippets.

@iamleeg
Created April 22, 2013 12:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamleeg/5434531 to your computer and use it in GitHub Desktop.
Save iamleeg/5434531 to your computer and use it in GitHub Desktop.
Somewhat-safely add "category" methods to a class, only if they don't already exist.
//
// main.m
// DynamicCategories
//
// Created by Graham Lee on 22/04/2013.
// Copyright (c) 2013 Graham Lee.
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#import <objc/runtime.h>
#import <Foundation/Foundation.h>
@protocol DynamicCategory <NSObject>
+ (NSArray *)methodsToAdd;
@end
BOOL class_addCategory(Class targetClass, Class sourceClass, BOOL replaceExistingMethods);
@interface TargetClass1 : NSObject
@end
@interface TargetClass2 : NSObject
@end
@interface TargetClass3 : NSObject
@end
@interface SourceClassWithYesReturn : NSObject <DynamicCategory>
- (BOOL)addedMethod;
@end
@interface SourceClassWithNoReturn : NSObject <DynamicCategory>
- (BOOL)addedMethod;
@end
TEST_CASE("addCategory/AddMethods", "class_addCategory can add methods that don't already exist")
{
TargetClass1 *a = [TargetClass1 new];
REQUIRE([a respondsToSelector: @selector(addedMethod)] == NO);
REQUIRE(class_addCategory([TargetClass1 class], [SourceClassWithYesReturn class], NO) == YES);
REQUIRE([a respondsToSelector: @selector(addedMethod)] == YES);
REQUIRE([(id)a addedMethod] == YES);
}
TEST_CASE("addCategory/NoReplacement", "don't replace existing methods if that's requested")
{
TargetClass2 *a = [TargetClass2 new];
class_addCategory([TargetClass2 class], [SourceClassWithNoReturn class], NO);
REQUIRE(class_addCategory([TargetClass2 class], [SourceClassWithYesReturn class], NO) == NO);
REQUIRE([(id)a addedMethod] == NO);
}
TEST_CASE("addCategory/WithReplacement", "replace existing methods if that's requested")
{
TargetClass3 *a = [TargetClass3 new];
class_addCategory([TargetClass3 class], [SourceClassWithNoReturn class], NO);
REQUIRE(class_addCategory([TargetClass3 class], [SourceClassWithYesReturn class], YES) == YES);
REQUIRE([(id)a addedMethod] == YES);
}
@implementation TargetClass1
@end
@implementation TargetClass2
@end
@implementation TargetClass3
@end
@implementation SourceClassWithYesReturn
- (BOOL)addedMethod
{
return YES;
}
+ (NSArray *)methodsToAdd
{
return @[ @"addedMethod" ];
}
@end
@implementation SourceClassWithNoReturn
- (BOOL)addedMethod
{
return NO;
}
+ (NSArray *)methodsToAdd
{
return @[ @"addedMethod" ];
}
@end
BOOL class_addCategory(Class targetClass, Class sourceClass, BOOL replaceExistingMethods)
{
NSCParameterAssert(class_conformsToProtocol(sourceClass, @protocol(DynamicCategory)));
NSArray *methodsToAdd = [sourceClass methodsToAdd];
if (!replaceExistingMethods)
{
__block BOOL foundExistingMethod = NO;
[methodsToAdd enumerateObjectsUsingBlock: ^(NSString *methodName, NSUInteger idx, BOOL *stop) {
SEL selectorToAdd = NSSelectorFromString(methodName);
if ([targetClass instancesRespondToSelector: selectorToAdd])
{
foundExistingMethod = YES;
*stop = YES;
}
}];
if (foundExistingMethod)
{
return NO;
}
}
for (NSString *methodName in [sourceClass methodsToAdd])
{
SEL methodSelector = NSSelectorFromString(methodName);
Method method = class_getInstanceMethod(sourceClass, methodSelector);
IMP methodImplementation = method_getImplementation(method);
const char *methodTypes = method_getTypeEncoding(method);
NSCAssert(method != NULL, @"Attempt to add nonexistent method %@ from class %@", methodName, NSStringFromClass(sourceClass));
class_replaceMethod(targetClass, methodSelector, methodImplementation, methodTypes);
}
return YES;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment