NSObject+YYAdd的学习
看到这个分类,直接无法想象,还对NSObject进行了一些自己方法的封装。写了那么多年的代码从来没有用到过或想到过,想要对NSObject进行扩展。YY大神,你可以的。
INIT_INV
在实现方法中,首先看到的是一个宏定义:
#define INIT_INV(_last_arg_, _return_) \
NSMethodSignature * sig = [self methodSignatureForSelector:sel]; \
if (!sig) { [self doesNotRecognizeSelector:sel]; return _return_; } \
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig]; \
if (!inv) { [self doesNotRecognizeSelector:sel]; return _return_; } \
[inv setTarget:self]; \
[inv setSelector:sel]; \
va_list args; \
va_start(args, _last_arg_); \
[NSObject setInv:inv withSig:sig andArgs:args]; \
va_end(args);
将方法
- (id)performSelectorWithArgs:(SEL)sel, ...{
INIT_INV(sel, nil);
[inv invoke];
return [NSObject getReturnFromInv:inv withSig:sig];
}
展开为:
- (id)performSelectorWithArgs:(SEL)sel, ...
{
NSMethodSignature * sig = [self methodSignatureForSelector:sel];
if (!sig) { [self doesNotRecognizeSelector:sel]; return nil; }
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];
if (!inv) { [self doesNotRecognizeSelector:sel]; return nil; }
[inv setTarget:self];
[inv setSelector:sel];
va_list args;
va_start(args, sel);
[NSObject setInv:inv withSig:sig andArgs:args];
va_end(args);
[inv invoke];
return [NSObject getReturnFromInv:inv withSig:sig];
}
其中的- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector;
的作用是生成一个有效的方法签名。在runtime中objc_msgSend调用时,查找SEL的IML的过程:
根据NSMethodSignature创建NSInvocation实例,
+ (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)sig;
. 为进行forwardInvocation:准备。
[NSObject setInv:inv withSig:sig andArgs:args];
调用了方法:
+ (void)setInv:(NSInvocation *)inv withSig:(NSMethodSignature *)sig andArgs:(va_list)args {
NSUInteger count = [sig numberOfArguments];
for (int index = 2; index < count; index++) {
char *type = (char *)[sig getArgumentTypeAtIndex:index];
while (*type == 'r' || // const
*type == 'n' || // in
*type == 'N' || // inout
*type == 'o' || // out
*type == 'O' || // bycopy
*type == 'R' || // byref
*type == 'V') { // oneway
type++; // cutoff useless prefix
}
BOOL unsupportedType = NO;
switch (*type) {
case 'v': // 1: void
case 'B': // 1: bool
case 'c': // 1: char / BOOL
case 'C': // 1: unsigned char
case 's': // 2: short
case 'S': // 2: unsigned short
case 'i': // 4: int / NSInteger(32bit)
case 'I': // 4: unsigned int / NSUInteger(32bit)
case 'l': // 4: long(32bit)
case 'L': // 4: unsigned long(32bit)
{ // 'char' and 'short' will be promoted to 'int'.
int arg = va_arg(args, int);
[inv setArgument:&arg atIndex:index];
} break;
case 'q': // 8: long long / long(64bit) / NSInteger(64bit)
case 'Q': // 8: unsigned long long / unsigned long(64bit) / NSUInteger(64bit)
{
long long arg = va_arg(args, long long);
[inv setArgument:&arg atIndex:index];
} break;
case 'f': // 4: float / CGFloat(32bit)
{ // 'float' will be promoted to 'double'.
double arg = va_arg(args, double);
float argf = arg;
[inv setArgument:&argf atIndex:index];
} break;
case 'd': // 8: double / CGFloat(64bit)
{
double arg = va_arg(args, double);
[inv setArgument:&arg atIndex:index];
} break;
case 'D': // 16: long double
{
long double arg = va_arg(args, long double);
[inv setArgument:&arg atIndex:index];
} break;
case '*': // char *
case '^': // pointer
{
void *arg = va_arg(args, void *);
[inv setArgument:&arg atIndex:index];
} break;
case ':': // SEL
{
SEL arg = va_arg(args, SEL);
[inv setArgument:&arg atIndex:index];
} break;
case '#': // Class
{
Class arg = va_arg(args, Class);
[inv setArgument:&arg atIndex:index];
} break;
case '@': // id
{
id arg = va_arg(args, id);
[inv setArgument:&arg atIndex:index];
} break;
case '{': // struct
{
if (strcmp(type, @encode(CGPoint)) == 0) {
CGPoint arg = va_arg(args, CGPoint);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(CGSize)) == 0) {
CGSize arg = va_arg(args, CGSize);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(CGRect)) == 0) {
CGRect arg = va_arg(args, CGRect);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(CGVector)) == 0) {
CGVector arg = va_arg(args, CGVector);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(CGAffineTransform)) == 0) {
CGAffineTransform arg = va_arg(args, CGAffineTransform);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(CATransform3D)) == 0) {
CATransform3D arg = va_arg(args, CATransform3D);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(NSRange)) == 0) {
NSRange arg = va_arg(args, NSRange);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(UIOffset)) == 0) {
UIOffset arg = va_arg(args, UIOffset);
[inv setArgument:&arg atIndex:index];
} else if (strcmp(type, @encode(UIEdgeInsets)) == 0) {
UIEdgeInsets arg = va_arg(args, UIEdgeInsets);
[inv setArgument:&arg atIndex:index];
} else {
unsupportedType = YES;
}
} break;
case '(': // union
{
unsupportedType = YES;
} break;
case '[': // array
{
unsupportedType = YES;
} break;
default: // what?!
{
unsupportedType = YES;
} break;
}
if (unsupportedType) {
// Try with some dummy type...
NSUInteger size = 0;
NSGetSizeAndAlignment(type, &size, NULL);
#define case_size(_size_) \
else if (size <= 4 * _size_ ) { \
struct dummy { char tmp[4 * _size_]; }; \
struct dummy arg = va_arg(args, struct dummy); \
[inv setArgument:&arg atIndex:index]; \
}
if (size == 0) { }
case_size( 1) case_size( 2) case_size( 3) case_size( 4)
case_size( 5) case_size( 6) case_size( 7) case_size( 8)
case_size( 9) case_size(10) case_size(11) case_size(12)
case_size(13) case_size(14) case_size(15) case_size(16)
case_size(17) case_size(18) case_size(19) case_size(20)
case_size(21) case_size(22) case_size(23) case_size(24)
case_size(25) case_size(26) case_size(27) case_size(28)
case_size(29) case_size(30) case_size(31) case_size(32)
case_size(33) case_size(34) case_size(35) case_size(36)
case_size(37) case_size(38) case_size(39) case_size(40)
case_size(41) case_size(42) case_size(43) case_size(44)
case_size(45) case_size(46) case_size(47) case_size(48)
case_size(49) case_size(50) case_size(51) case_size(52)
case_size(53) case_size(54) case_size(55) case_size(56)
case_size(57) case_size(58) case_size(59) case_size(60)
case_size(61) case_size(62) case_size(63) case_size(64)
else {
/*
Larger than 256 byte?! I don't want to deal with this stuff up...
Ignore this argument.
*/
struct dummy {char tmp;};
for (int i = 0; i < size; i++) va_arg(args, struct dummy);
NSLog(@"YYKit performSelectorWithArgs unsupported type:%s (%lu bytes)",
[sig getArgumentTypeAtIndex:index],(unsigned long)size);
}
#undef case_size
}
}
}
根据多个入参的第3个参数开始,不同的字符设置不同的数据类型。
[inv invoke];
调用方法。然后执行[NSObject getReturnFromInv:inv withSig:sig]
,根据标志转化为不同的数据类型,返回不同类型的值。
+ (id)getReturnFromInv:(NSInvocation *)inv withSig:(NSMethodSignature *)sig {
NSUInteger length = [sig methodReturnLength];
if (length == 0) return nil;
char *type = (char *)[sig methodReturnType];
while (*type == 'r' || // const
*type == 'n' || // in
*type == 'N' || // inout
*type == 'o' || // out
*type == 'O' || // bycopy
*type == 'R' || // byref
*type == 'V') { // oneway
type++; // cutoff useless prefix
}
#define return_with_number(_type_) \
do { \
_type_ ret; \
[inv getReturnValue:&ret]; \
return @(ret); \
} while (0)
switch (*type) {
case 'v': return nil; // void
case 'B': return_with_number(bool);
case 'c': return_with_number(char);
case 'C': return_with_number(unsigned char);
case 's': return_with_number(short);
case 'S': return_with_number(unsigned short);
case 'i': return_with_number(int);
case 'I': return_with_number(unsigned int);
case 'l': return_with_number(int);
case 'L': return_with_number(unsigned int);
case 'q': return_with_number(long long);
case 'Q': return_with_number(unsigned long long);
case 'f': return_with_number(float);
case 'd': return_with_number(double);
case 'D': { // long double
long double ret;
[inv getReturnValue:&ret];
return [NSNumber numberWithDouble:ret];
};
case '@': { // id
void *ret;
[inv getReturnValue:&ret];
return (__bridge id)(ret);
};
case '#': { // Class
Class ret = nil;
[inv getReturnValue:&ret];
return ret;
};
default: { // struct / union / SEL / void* / unknown
const char *objCType = [sig methodReturnType];
char *buf = calloc(1, length);
if (!buf) return nil;
[inv getReturnValue:buf];
NSValue *value = [NSValue valueWithBytes:buf objCType:objCType];
free(buf);
return value;
};
}
#undef return_with_number
}
swizzle 交换实例和类方法
+ (BOOL)swizzleInstanceMethod:(SEL)originalSel with:(SEL)newSel
交换实例方法
在交互实例方法之前,需要先添加方法的实现,然后再调用method_exchangeImplementations(Method _Nonnull m1, Method _Nonnull m2)
。
+ (BOOL)swizzleClassMethod:(SEL)originalSel with:(SEL)newSel
交换类方法
感觉将runtime的使用都封装了一层。 一直觉得Runtime没有用处,或者是没有机会去优化代码,一直在码代码。希望那天可以改造下代码,用用高大上的runtime。
KVO
监听key path后执行block,并retain了block。提供了根据key path移除block或移除所有的block。并且支持相同的key,保存不同的block。
封装了系统的KVO,比系统的KVO使用上方便了很多。
在移除block的时候使用了
NSMutableDictionary *dic = [self _yy_allNSObjectObserverBlocks];
[dic enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSArray *arr, BOOL *stop) {
[arr enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
[self removeObserver:obj forKeyPath:key];
}];
}];
[dic removeAllObjects];
采用了枚举的方式列举所有的值,并进行移除。
// END