method swizzling 和 isa swizzling 是一回事吗?如果不是,那么什么是 swizzling?
问问题
3403 次
1 回答
33
方法混搭
Method swizzling在运行时交换一个类的两个方法的实现。这将影响修改后的类的每个已创建或将要创建的实例。
示例:假设您为 NSString 编写了一个类别:
@interface NSString (Swizzling)
@end
@implementation NSString (Swizzling)
- (NSString *)swizzled_uppercaseString {
//when the method is swizzled, the original method will be called
//with swizzled_uppercaseString (so this will not create a stack overflow).
NSString *result = [self swizzled_uppercaseString];
// our custom code
result = [result stringByAppendingString:@" (swizzled)"];
return result;
}
@end
然后,您可以将 -method 的实现与uppercaseString
-method交换swizzled_uppercaseString
,以便在调用swizzled_uppercaseString
时执行该方法的实现。(并且在调用时执行uppercaseString
的原始实现):uppercaseString
swizzled_uppercaseString
#import <objc/runtime.h>
NSString *sample = @"abc";
// original method is called:
NSLog([sample uppercaseString]);
//Obtaining original and swizzled method:
original = class_getInstanceMethod([NSString class], @selector(uppercaseString));
swizzled = class_getInstanceMethod([NSString class], @selector(swizzled_uppercaseString));
//Exchange implementations here:
method_exchangeImplementations(original, swizzled);
// swizzled method is called:
NSLog([sample uppercaseString]); //prints "ABC (swizzled)"
ISA 调酒
ISA swizzling 修改单个对象的属性,即 ISA ('is a') 属性,它描述了对象的类,因此您可以在运行时将给定单个对象的类型与另一种类型交换。
示例:假设您有这样的类结构:
@interface Sample : NSObject
@property (nonatomic) NSString *sampleStringToLoad;
@end
@implementation Sample
@synthesize sampleStringToLoad;
@end
@interface SampleWithStringLoader :NSObject
@property (nonatomic) NSString *sampleStringToLoad;
-(void)loadString;
@end
@implementation SampleWithStringLoader
@synthesize sampleStringToLoad;
-(void)loadString {
self.sampleStringToLoad = @"abc";
}
@end
然后,您可以将类设置为SampleWithStringLoader
,因此sampleStringToLoad
-method 变得可用:
#import <objc/runtime.h>
Sample *sample = [Sample new];
// switch isa to new class:
object_setClass(sample, [SampleWithStringLoader class]);
// invoke method that is only in SampleWithStringLoader:
[sample performSelector:@selector(loadString)];
// switch isa back to original class:
object_setClass(sample,[Sample class]);
// Prints 'abc':
NSLog(sample.sampleStringToLoad);
于 2016-08-10T15:47:01.117 回答