废土博客
目录
如何在低版本调用高版本的API,同时完全不影响高版本API的功能
<h3 id="1">如何在低版本调用高版本的API,同时完全不影响高版本API的功能</h3>
要满足高版本API能够在低版本调用的必要条件就是自己实现低版本API中没有的实现,那么如何实现呢。
在OC中扩展一个已有类一般有两种方法: Subclass
和 Category
。显然在这里使用Category
会比较合适
下面举个例子NSOperation 类有一个属性 name,这个属性是NS_AVAILABLE(10_10, 8_0)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL nameSEL = @selector(name);
SEL setNameSEL = @selector(setName:);
Method nameMethod = class_getInstanceMethod(class, nameSEL);
Method setNameMethod = class_getInstanceMethod(class, setNameSEL);
if (!nameMethod)
{
SEL xxxNameSEL = @selector(xxx_name);
Method xxxNameMethod = class_getInstanceMethod(class, xxxNameSEL);
class_addMethod(class, nameSEL, method_getImplementation(xxxNameMethod), method_getTypeEncoding(xxxNameMethod));
}
if (!setNameMethod)
{
SEL xxxSetNameSEL = @selector(xxx_setName:);
Method xxxSetNameMethod = class_getInstanceMethod(class, xxxSetNameSEL);
class_addMethod(class, setNameSEL, method_getImplementation(xxxSetNameMethod), method_getTypeEncoding(xxxSetNameMethod));
}
});
}
- (NSString*)xxx_name
{
return objc_getAssociatedObject(self, @"name");
}
- (void)xxx_setName:(NSString*)name
{
objc_setAssociatedObject(self, @"name", name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}