1. 消除NSNull
引起的crash
OC中給null發(fā)消息是會導(dǎo)致crash, 為了避免這個(gè)可以
給 NSNull 添加分類 NSNull+YFAdd.h
直接放到項(xiàng)目里就行了.
. m 實(shí)現(xiàn)代碼如下:
- (void)forwardInvocation:(NSInvocation *)invocation {
if ([self respondsToSelector:[invocation selector]]) {
[invocation invokeWithTarget:self];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
NSMethodSignature *sig = [[NSNull class] instanceMethodSignatureForSelector:selector];
if(sig == nil) {
sig = [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
}
return sig;
}
2. 手勢綁定block
UIGestureRecognizer+Block
[self.view addGestureRecognizer:[UITapGestureRecognizer gestureRecognizerWithBlock:^(id gestureRecognizer) {
//...這里面寫代碼, 不用@(selector)
}]];
.m 代碼如下
#import "UIGestureRecognizer+Block.h"
static const int AssociatedTarget_key;
@implementation UIGestureRecognizer (Block)
+ (instancetype)yf_gestureRecognizerWithBlock:(YFGestureBlock)block {
return [[self alloc] initWithBlock:block];
}
- (instancetype)initWithBlock:(YFGestureBlock)block {
self = [self init];
[self addBlock:block];
[self addTarget:self action:@selector(invoke:)];
return self;
}
- (void)addBlock:(YFGestureBlock)block {
if (block) {
objc_setAssociatedObject(self, &AssociatedTarget_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
}
- (void)invoke:(id)sender {
YFGestureBlock block = objc_getAssociatedObject(self, &AssociatedTarget_key);
if (block) {
block(sender);
}
}
@end