Objc Runtime在項目中該怎麼用html
從如下四個方面講述Objc Runtime在項目中的使用場景,使用的例子來自於github上的開源項目FDFullscreenPopGesture、GVUserDefaults 以及系統中KVO的底層實現例子git
Method Swizzling
簡單的講就是方法替換,是一種hook技術,一個典型的Method Swizzling
例子以下,註釋部分說明了爲何這麼作。github
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
// When swizzling a class method, use the following:
// Class class = object_getClass((id)self);
SEL originalSelector = @selector(viewWillAppear:);
SEL swizzledSelector = @selector(xxx_viewWillAppear:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// 在進行Swizzling的時候,咱們須要用class_addMethod先進行判斷一下原有類中是否有要替換的方法的實現。
BOOL didAddMethod = class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
// 若是class_addMethod返回YES,說明當前類中沒有要替換方法的實現,咱們須要在父類中去尋找。這個時候就須要用到method_getImplementation去獲取class_getInstanceMethod裏面的方法實現。而後再進行class_replaceMethod來實現Swizzling。
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
// 若是class_addMethod返回NO,說明當前類中有要替換方法的實現,因此能夠直接進行替換,調用method_exchangeImplementations便可實現Swizzling。
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
#pragma mark - Method Swizzling
- (void)xxx_viewWillAppear:(BOOL)animated {
// 因爲咱們進行了Swizzling,因此其實在原來的- (void)viewWillAppear:(BOOL)animated方法中,調用的是- (void)xxx_viewWillAppear:(BOOL)animated方法的實現。因此不會形成死循環。相反的,若是這裏把[self xxx_viewWillAppear:animated];改爲[self viewWillAppear:animated];就會形成死循環。由於外面調用[self viewWillAppear:animated];的時候,會交換方法走到[self xxx_viewWillAppear:animated];這個方法實現中來,而後這裏又去調用[self viewWillAppear:animated],就會形成死循環了。
[self xxx_viewWillAppear:animated];
NSLog(@"viewWillAppear: %@", self);
}
複製代碼
FDFullscreenPopGesture 這個庫使用的就是Method Swizzling
技術實現的全屏手勢返回的效果api
UINavigationController (FDFullscreenPopGesture)
分類的load
方法中替換了系統的pushViewController:animated:
方法app
+ (void)load
{
// Inject "-pushViewController:animated:"
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(pushViewController:animated:);
SEL swizzledSelector = @selector(fd_pushViewController:animated:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (success) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
複製代碼
在替換的方法中禁用了系統的邊緣返回手勢,添加了自定義的手勢來處理less
- (void)fd_pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (![self.interactivePopGestureRecognizer.view.gestureRecognizers containsObject:self.fd_fullscreenPopGestureRecognizer]) {
// Add our own gesture recognizer to where the onboard screen edge pan gesture recognizer is attached to.
[self.interactivePopGestureRecognizer.view addGestureRecognizer:self.fd_fullscreenPopGestureRecognizer];
// Forward the gesture events to the private handler of the onboard gesture recognizer.
NSArray *internalTargets = [self.interactivePopGestureRecognizer valueForKey:@"targets"];
id internalTarget = [internalTargets.firstObject valueForKey:@"target"];
SEL internalAction = NSSelectorFromString(@"handleNavigationTransition:");
self.fd_fullscreenPopGestureRecognizer.delegate = self.fd_popGestureRecognizerDelegate;
[self.fd_fullscreenPopGestureRecognizer addTarget:internalTarget action:internalAction];
// Disable the onboard gesture recognizer.
self.interactivePopGestureRecognizer.enabled = NO;
}
// Handle perferred navigation bar appearance.
[self fd_setupViewControllerBasedNavigationBarAppearanceIfNeeded:viewController];
// Forward to primary implementation.
if (![self.viewControllers containsObject:viewController]) {
[self fd_pushViewController:viewController animated:animated];
}
}
複製代碼
而後在自定義的手勢的回調方法gestureRecognizerShouldBegin
中處理手勢的返回ide
- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer
{
// Ignore when no view controller is pushed into the navigation stack.
if (self.navigationController.viewControllers.count <= 1) {
return NO;
}
// Ignore when the active view controller doesn't allow interactive pop.
UIViewController *topViewController = self.navigationController.viewControllers.lastObject;
if (topViewController.fd_interactivePopDisabled) {
return NO;
}
// Ignore when the beginning location is beyond max allowed initial distance to left edge.
CGPoint beginningLocation = [gestureRecognizer locationInView:gestureRecognizer.view];
CGFloat maxAllowedInitialDistance = topViewController.fd_interactivePopMaxAllowedInitialDistanceToLeftEdge;
if (maxAllowedInitialDistance > 0 && beginningLocation.x > maxAllowedInitialDistance) {
return NO;
}
// Ignore pan gesture when the navigation controller is currently in transition.
if ([[self.navigationController valueForKey:@"_isTransitioning"] boolValue]) {
return NO;
}
// Prevent calling the handler when the gesture begins in an opposite direction.
CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view];
BOOL isLeftToRight = [UIApplication sharedApplication].userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionLeftToRight;
CGFloat multiplier = isLeftToRight ? 1 : - 1;
if ((translation.x * multiplier) <= 0) {
return NO;
}
return YES;
}
複製代碼
GVUserDefaults 是一個屬性和NSUserDefaults
之間實現自動寫入和讀取的開源庫,該庫(當前最新版本 1.0.2)使用到的技術就是動態方法添加,項目中使用到的主要技術點列舉以下:函數
class_copyPropertyList
獲取類的property列表property_getName
獲取property名稱property_getAttributes
獲取property的屬性,能夠參考Property Attribute Description Examplessel_registerName
註冊SELclass_addMethod
添加方法主要看generateAccessorMethods
方法的實現,該方法自動生成屬性對應的Getter和Setter方法,關鍵的地方有添加了註釋oop
- (void)generateAccessorMethods {
unsigned int count = 0;
// 獲取類的屬性列表
objc_property_t *properties = class_copyPropertyList([self class], &count);
self.mapping = [NSMutableDictionary dictionary];
for (int i = 0; i < count; ++i) {
objc_property_t property = properties[i];
// 獲取property名稱
const char *name = property_getName(property);
// 獲取property的屬性
const char *attributes = property_getAttributes(property);
char *getter = strstr(attributes, ",G");
if (getter) {
// getter修飾的屬性:@property (nonatomic, getter=zytCustomerGetter) float customerGetter; -> "Tf,N,GzytCustomerGetter"
getter = strdup(getter + 2);
getter = strsep(&getter, ",");
} else {
getter = strdup(name);
}
SEL getterSel = sel_registerName(getter);
free(getter);
char *setter = strstr(attributes, ",S");
if (setter) {
// setter 修飾的屬性:@property (nonatomic, setter=zytCustomerSetter:) float customerSetter; -> Tf,N,SzytCustomerSetter:
setter = strdup(setter + 2);
setter = strsep(&setter, ",");
} else {
asprintf(&setter, "set%c%s:", toupper(name[0]), name + 1);
}
// 註冊SEL
SEL setterSel = sel_registerName(setter);
free(setter);
// 同一個屬性的`Getter`或者`Setter`方法在`self.mapping`對應的值是同樣的,
NSString *key = [self defaultsKeyForPropertyNamed:name];
[self.mapping setValue:key forKey:NSStringFromSelector(getterSel)];
[self.mapping setValue:key forKey:NSStringFromSelector(setterSel)];
IMP getterImp = NULL;
IMP setterImp = NULL;
char type = attributes[1];
switch (type) {
case Short:
case Long:
case LongLong:
case UnsignedChar:
case UnsignedShort:
case UnsignedInt:
case UnsignedLong:
case UnsignedLongLong:
getterImp = (IMP)longLongGetter;
setterImp = (IMP)longLongSetter;
break;
case Bool:
case Char:
getterImp = (IMP)boolGetter;
setterImp = (IMP)boolSetter;
break;
case Int:
getterImp = (IMP)integerGetter;
setterImp = (IMP)integerSetter;
break;
case Float:
getterImp = (IMP)floatGetter;
setterImp = (IMP)floatSetter;
break;
case Double:
getterImp = (IMP)doubleGetter;
setterImp = (IMP)doubleSetter;
break;
case Object:
getterImp = (IMP)objectGetter;
setterImp = (IMP)objectSetter;
break;
default:
free(properties);
[NSException raise:NSInternalInconsistencyException format:@"Unsupported type of property \"%s\" in class %@", name, self];
break;
}
char types[5];
snprintf(types, 4, "%c@:", type);
// 添加方法
class_addMethod([self class], getterSel, getterImp, types);
snprintf(types, 5, "v@:%c", type);
// 添加方法
class_addMethod([self class], setterSel, setterImp, types);
}
free(properties);
}
複製代碼
其中property_getAttributes(property)
獲取到的property屬性字符串的第二位的類型信息能夠參考Apple官方文檔ui
對應的程序中定義了TypeEncodings
枚舉
enum TypeEncodings {
Char = 'c',
Bool = 'B',
Short = 's',
Int = 'i',
Long = 'l',
LongLong = 'q',
UnsignedChar = 'C',
UnsignedShort = 'S',
UnsignedInt = 'I',
UnsignedLong = 'L',
UnsignedLongLong = 'Q',
Float = 'f',
Double = 'd',
Object = '@'
};
複製代碼
好比對象類型的屬性,通過以下的處理
getterImp = (IMP)objectGetter;
setterImp = (IMP)objectSetter;
//...
class_addMethod([self class], getterSel, getterImp, types);
class_addMethod([self class], setterSel, setterImp, types);
複製代碼
使用屬性Getter
或者Setter
最終會調用如下的方法
static id objectGetter(GVUserDefaults *self, SEL _cmd) {
NSString *key = [self defaultsKeyForSelector:_cmd];
return [self.userDefaults objectForKey:key];
}
static void objectSetter(GVUserDefaults *self, SEL _cmd, id object) {
NSString *key = [self defaultsKeyForSelector:_cmd];
if (object) {
[self.userDefaults setObject:object forKey:key];
} else {
[self.userDefaults removeObjectForKey:key];
}
}
複製代碼
這裏用到的defaultsKeyForSelector
方法定義以下,把屬性Getter
或者Setter
方法映射爲對應的屬性的保存的Key的字符串,同一個屬性的Getter
或者Setter
方法在self.mapping
對應的值是同樣的,詳細的保存映射信息到self.mapping
中能夠查看generateAccessorMethods
方法。
- (NSString *)defaultsKeyForSelector:(SEL)selector {
return [self.mapping objectForKey:NSStringFromSelector(selector)];
}
複製代碼
系統的KVO的實現是基於isa swizzling實現的,建立一個NSObject
的分類模擬KVO的實現,主要用到技術點
objc_allocateClassPair
添加一個類objc_registerClassPair
註冊添加的類object_setClass
修改當前類的class,也就是isa指針class_addMethod
類動態添加方法objc_msgSend
使用底層C的方法執行方法調用objc_setAssociatedObject
、objc_getAssociatedObject
設置和獲取關聯對象主要的思路以下:
- (void)ytt_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
方法是相似系統添加KVO監聽的方法,該方法中
observer
和 keyPath
參數;動態的建立和註冊KVO類;object_setClass
修改當前對象的isa
指針;class_addMethod
動態添加一個監聽的keyPath
屬性對應的Setter
方法keyPath
屬性對應的Setter
方法的實現:
object_setClass
修改對象的isa
指針爲原始的類,後面使用Setter
方法設置新值調用的objc_msgSend
方法才能正確執行;objc_getAssociatedObject
獲取綁定的關聯對象中keyPath
,還原出Getter
方法和Setter
方法,使用Getter
方法獲取舊的值,使用Setter
方法設置新值;objc_getAssociatedObject
獲取綁定的關聯對象中observer
,向 observer 對象發送屬性變換的消息;isa
指針爲動態建立的KVO類,下一次的流程才能正常執行@implementation NSObject (YTT_KVO)
- (void)ytt_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context {
// 保存keypath
objc_setAssociatedObject(self, "keyPath", keyPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
objc_setAssociatedObject(self, "observer", observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// 獲取當前類
Class selfClass = self.class;
// 動態建立KVO類
const char * className = NSStringFromClass(selfClass).UTF8String;
char kvoClassName[1000];
sprintf(kvoClassName, "%s%s", "YTT_KVO_", className);
Class kvoClass = objc_allocateClassPair(selfClass, kvoClassName, 0);
if (!kvoClass) {
// Nil if the class could not be created (for example, the desired name is already in use).
kvoClass = NSClassFromString([NSString stringWithUTF8String:kvoClassName]);
}
objc_registerClassPair(kvoClass);
// 修改當前類指向爲動態建立的KVO子類,kvoClass繼承自selfClass
object_setClass(self, kvoClass);
// 動態添加一個方法:setXxx()
SEL sel = NSSelectorFromString([NSString stringWithFormat:@"set%@:", keyPath.capitalizedString]);
class_addMethod(kvoClass, sel, (IMP)setValue, NULL);
}
void setValue(id self, SEL _cmd, id value) {
// 保存當前的Class,重置Class使用
Class selfClass = [self class];
// 設置Class爲原始Class
object_setClass(self, [self superclass]);
// 獲取keyPath
NSString* keyPath = objc_getAssociatedObject(self, "keyPath");
// KVO 回調參數
NSMutableDictionary* change = [NSMutableDictionary dictionary];
change[NSKeyValueChangeNewKey] = value;
// 獲取舊的值
SEL getSel = NSSelectorFromString([NSString stringWithFormat:@"%@", keyPath]);
if ([self respondsToSelector:getSel]) {
id ret = ((id(*)(id, SEL, id))objc_msgSend)(self, getSel, value);
if (ret) {
change[NSKeyValueChangeOldKey] = ret;
}
}
// 給原始類設置數據
SEL setSel = NSSelectorFromString([NSString stringWithFormat:@"set%@:", keyPath.capitalizedString]);
if ([self respondsToSelector:setSel]) {
((void(*)(id, SEL, id))objc_msgSend)(self, setSel, value);
}
// 發送通知
id observer = objc_getAssociatedObject(self, "observer");
SEL observerSel = @selector(ytt_observeValueForKeyPath:ofObject:change:context:);
if ([observer respondsToSelector:observerSel]) {
((void(*) (id, SEL, NSString*, id, id ,id))(void *)objc_msgSend)(observer, observerSel, keyPath, self, change, nil);
}
// 重置class指針,這樣再次調用對象方法會走到這裏面
object_setClass(self, selfClass);
}
@end
複製代碼
消息轉發的步驟有如下四個:
resolveClassMethod:(SEL)sel
和resolveInstanceMethod:(SEL)sel
處理類方法和實例方法,能夠在該方法中使用class_addMethod
動態添加方法處理,返回YES表示該步驟可處理,不然表示不可處理,繼續執行下一步forwardingTargetForSelector:(SEL)aSelector
方法返回一個能夠處理該消息的對象完成消息的轉發處理forwardInvocation:(NSInvocation *)anInvocation
,若是以上兩個步驟都不能處理,最終會執行到這一步,anInvocation對象包含了消息詳細信息,包括id target
、SEL selector
、參數和返回值信息等等。該方法須要和methodSignatureForSelector:(SEL)aSelector
方法一塊兒使用,可使用NSInvocation
的實例方法invokeWithTarget:(id)target
完成消息的轉發NSObject
的方法doesNotRecognizeSelector:(SEL)aSelector
,拋出一個unrecognized selector sent to instance xxx
的異常GVUserDefaults 是一個屬性和NSUserDefaults
之間實現自動寫入和讀取的開源庫,該庫(0.4.1以前的舊版本)使用到的技術就是消息轉發
GVUserDefaults
庫中使用的是消息轉發中的動態方法解析resolveInstanceMethod
方法,Setter
方法的消息轉發給accessorSetter
C函數處理,Getter
方法的消息轉發給accessorGetter
C函數處理,accessorSetter
和accessorGetter
最終仍是經過NSUserDefaults
實現屬性對應的Key的設置和讀取,關鍵的代碼以下:
+ (BOOL)resolveInstanceMethod:(SEL)aSEL {
NSString *method = NSStringFromSelector(aSEL);
if ([method isEqualToString:@"transformKey:"] || [method isEqualToString:@"setupDefaults"]) {
// Prevent endless loop for optional (and missing) category methods
return [super resolveInstanceMethod:aSEL];
}
if ([method hasPrefix:@"set"]) {
class_addMethod([self class], aSEL, (IMP) accessorSetter, "v@:@");
return YES;
} else {
class_addMethod([self class], aSEL, (IMP) accessorGetter, "@@:");
return YES;
}
}
- (NSString *)_transformKey:(NSString *)key {
if ([self respondsToSelector:@selector(transformKey:)]) {
return [self performSelector:@selector(transformKey:) withObject:key];
}
return key;
}
id accessorGetter(GVUserDefaults *self, SEL _cmd) {
NSString *key = NSStringFromSelector(_cmd);
key = [self _transformKey:key];
return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}
void accessorSetter(GVUserDefaults *self, SEL _cmd, id newValue) {
NSString *method = NSStringFromSelector(_cmd);
NSString *key = [[method stringByReplacingCharactersInRange:NSMakeRange(0, 3) withString:@""] stringByReplacingOccurrencesOfString:@":" withString:@""];
key = [key stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[key substringToIndex:1] lowercaseString]];
key = [self _transformKey:key];
// Set value of the key anID to newValue
[[NSUserDefaults standardUserDefaults] setObject:newValue forKey:key];
}
複製代碼