我想在ios3.x中使用一些ios4.x的东西。我知道如何实现它们,我假设我的实现比苹果的慢或者可能有更多的bug,所以我想在任何时候使用苹果的。
@implementation NSDictionary (NSDictionary_4)
void compatability_method(Class class, SEL newer_version_selector, SEL compatability_selector) {
Method existingMethod = class_getInstanceMethod(class, newer_version_selector);
if (!existingMethod) {
Method compatabilityMethod = class_getInstanceMethod(class, compatability_selector);
class_replaceMethod(class, newer_version_selector, method_getImplementation(compatabilityMethod), method_getTypeEncoding(compatabilityMethod));
}
}
+(void)load {
if (self == [NSDictionary class]) {
compatability_method(self, @selector(enumerateKeysAndObjectsUsingBlock:), @selector(four_enumerateKeysAndObjectsUsingBlock:));
}
}
-(void)four_enumerateKeysAndObjectsUsingBlock:(void (^)(id key, id obj, BOOL *stop))block {
BOOL stop = false;
for (id key in self) {
block(key, [self objectForKey:key], &stop);
if (stop) {
break;
}
}
}
@end
如果这是个坏主意,有什么更好的办法?
(如果它是理智的,但代码有点离谱,我也想知道这一点…但我更感兴趣的是知道,如果整个想法是体面的,或者如果这整个类型的构造应该避免)