Objective-C 的 runtime 機制非常強大,本文透過四個實用範例,示範如何動態添加屬性、添加代理、置換方法,以及檢索協議方法。
.h 檔宣告:
@interface UIWebView (LoadProgress) @property (nonatomic, assign) NSInteger resourceCount; @end
.m 檔:先定義一個全域 key,再用關聯對象實作 getter 與 setter。
// resourceCount 關聯鍵
static void *s_resourceCountKey = &s_resourceCountKey;
@implementation UIWebView (LoadProgress)
@dynamic resourceCount;
- (NSInteger)resourceCount
{
NSNumber *resourceCountNumber = objc_getAssociatedObject(self, s_resourceCountKey);
if (! resourceCountNumber) {
return 0;
} else {
return [resourceCountNumber integerValue];
}
}
- (void)setResourceCount:(NSInteger)rCount
{
objc_setAssociatedObject(self, s_resourceCountKey,
[NSNumber numberWithInteger:rCount], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
完成後即可直接使用:webView.resourceCount = 10;
做法與添加屬性類似,透過關聯對象持有 delegate 即可(此處暫不展開)。
// 置換類方法
IMP HLSSwizzleClassSelector(Class clazz, SEL selector, IMP newImplementation)
{
Class metaClass = objc_getMetaClass(class_getName(clazz));
Method method = class_getClassMethod(metaClass, selector);
IMP origImp = method_getImplementation(method);
if (! origImp) { return NULL; }
class_replaceMethod(metaClass, selector, newImplementation, method_getTypeEncoding(method));
return origImp;
}
// 置換實例方法
IMP HLSSwizzleSelector(Class clazz, SEL selector, IMP newImplementation)
{
Method method = class_getInstanceMethod(clazz, selector);
IMP origImp = method_getImplementation(method);
if (! origImp) { return NULL; }
class_replaceMethod(clazz, selector, newImplementation, method_getTypeEncoding(method));
return origImp;
}
新方法的定義與在 +load 中完成初始化:
static id (*s_UIWebView__identifierForInitialRequest_Imp)(id, SEL, id, id, id) = NULL;
static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource);
+ (void)load
{
s_UIWebView__identifierForInitialRequest_Imp = (id (*)(id, SEL, id, id, id))HLSSwizzleSelector(
self, @selector(webView:identifierForInitialRequest:fromDataSource:),
(IMP)swizzled_UIWebView__identifierForInitialRequest_Imp);
}
#pragma mark Swizzled method implementations
static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource)
{
// 呼叫原方法
(*s_UIWebView__identifierForInitialRequest_Imp)(self, _cmd, webView, initialRequest, dataSource);
[self setResourceCount:self.resourceCount+1];
return [NSNumber numberWithInteger:self.resourceCount];
}
可直接定義到 NSObject 的 Category 中:
// [self implementsProtocol:@protocol(UIActionSheetDelegate)];
- (BOOL)implementsProtocol:(Protocol *)protocol
{
// 只關注 optional 方法,required 方法在編譯期就會檢查
unsigned int numberOfMethods = 0;
struct objc_method_description *methodDescriptions =
protocol_copyMethodDescriptionList(protocol, NO, YES, &numberOfMethods);
for (unsigned int i = 0; i < numberOfMethods; ++i) {
struct objc_method_description methodDescription = methodDescriptions[i];
SEL selector = methodDescription.name;
if (! class_getInstanceMethod([self class], selector)) {
return NO;
}
}
return YES;
}
這四個範例展示了 runtime 在動態特性與方法攔截上的威力,是深入 Objective-C 不可或缺的一塊拼圖。