我的应用程序需要同时在 iOS5(UIColor>>#copyWithZone
不存在)和 iOS6+(UIColor>>#copyWithZone
存在)上运行,所以我想出了以下内容:
@implementation UIColor(ios5CopyWithZone)
+ (void)initialize
{
// iOS5 dosn't include UIColor>>#copyWithZone so add it with class_addMethod.
// For iOS6+ class_addMethod fails as UIColor>>#copyWithZone already exists.
Class klass = [UIColor class];
Method methodToInstall = class_getInstanceMethod(klass, @selector(ios5CopyWithZone:));
class_addMethod(klass, @selector(copyWithZone:), method_getImplementation(methodToInstall), method_getTypeEncoding(methodToInstall));
}
// UIImage is immutable so can just return self.
// #retain to ensure we follow mem-management conventions
-(id)ios5CopyWithZone:(NSZone *)__unused zone
{
return [self retain];
}
@end
代码尝试UIColor>>#copyWithZone
使用运行时的class_addMethod
. 我不知道这是否比UIColor>>#copyWithZone
直接在类别中实现更好,但是阅读 Apple 的避免类别方法名称冲突意味着重新实现现有框架方法(即UIColor>>#copyWithZone
在 iOS6 中)是不好的做法。但是我意识到这+initialize
可能会践踏框架的+initialize
.