Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于消息转发 #1

Closed
HaloWang opened this issue Apr 28, 2016 · 2 comments
Closed

关于消息转发 #1

HaloWang opened this issue Apr 28, 2016 · 2 comments

Comments

@HaloWang
Copy link
Contributor

为什么消息转发中,你实现了 Cat+stoke 方法呢?

+ (void)stoke {
    Cat *carson = [[Cat alloc] init];
    [Cat performSelector:@selector(touch) withObject:nil afterDelay:0];
}

是需要我注释掉哪段代码吗?另外初始化一个 Cat 对象有什么作用呢?

@Tuccuay
Copy link
Owner

Tuccuay commented Apr 28, 2016

感谢指出,我尝试使用下面的代码可以正常工作。
如果你愿意的话,可以使用下面的代码提交一个 Pull requests 来修正这个错误。
当然,如果你有其它的方法也可以提交。

Cat.h

#import <Foundation/Foundation.h>

@interface Cat : NSObject

@end

Cat.m

#import "Cat.h"

@implementation Cat

// 这里演示的是 「类方法」,如果你需要处理 「对象方法」
// 把下面所有 "+" 开头的方法都改成 "-" 开头即可

// 在没有找到方法时,会先调用此方法,可用于动态添加方法
/*
+ (BOOL)resolveClassMethod:(SEL)sel {
return NO;
}
 */

// 如果上面返回 NO,就会进入这一步,用于指定备选响应此 SEL 的对象
// 如果返回 self 就会死循环
/*
+ (id)forwardingTargetForSelector:(SEL)aSelector {
    return nil;
}
 */

// 指定方法签名,若返回 nil,则不会进入下一步,而是无法处理消息
+ (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    if ([NSStringFromSelector(aSelector) isEqualToString:@"stoke"]) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }

    return [super methodSignatureForSelector:aSelector];
}

// 当实现了此方法后,-doesNotRecognizeSelector: 将不会被调用
// 如果要测试找不到方法,可以注释掉这一个方法
// 在这里进行消息转发
+ (void)forwardInvocation:(NSInvocation *)anInvocation {

    // 我们还可以改变方法选择器
    [anInvocation setSelector:@selector(touch)];
    // 改变方法选择器后,还需要指定是哪个对象的方法
    [anInvocation invokeWithTarget:self];
}

/*
+ (void)doesNotRecognizeSelector:(SEL)aSelector {
    NSLog(@"无法处理消息:%@", NSStringFromSelector(aSelector));
}
 */

+ (void)touch {
    NSLog(@"Cat 没有实现 stoke 方法,并且成功的转成了 touch 方法");
}

@end

@Tuccuay
Copy link
Owner

Tuccuay commented Apr 29, 2016

#2 merged

@Tuccuay Tuccuay closed this as completed Apr 29, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants