iOS 消除 NSNull 引起的 crash 和 手势绑定bl

2016-06-23  本文已影响200人  阿拉灯神钉

1. 消除NSNull引起的crash

OC中给null发消息是会导致crash, 为了避免这个可以
给 NSNull 添加分类 NSNull+YFAdd.h 直接放到项目里就行了.

. m 实现代码如下:

- (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
上一篇下一篇

猜你喜欢

热点阅读