Objective-C va_list 和选择器 [英] Objective-C va_list and selectors

查看:45
本文介绍了Objective-C va_list 和选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 @selectorperformSelector:(或类似的)与使用可变参数列表的方法一起使用?

Is it possible to use @selector and performSelector: (or similar) with methods using variable arguments list?

我正在编写一个可以分配一个委托来覆盖默认行为的类.在存在委托的情况下,对该类的实例进行的 select 方法调用将转发到相同的相应委托方法,其中一些使用可变参数列表.

I'm writing a class that can be assigned a delegate to override the default behavior. In the presence of a delegate select method calls made on an instance of that class will be forward to the same corresponding delegate method, some which use variable argument lists.

因此,例如,我需要能够创建检索 SEL 引用并使用如下方法向委托对象发送消息:

So, for instance, I need to be able to create retrieve SEL reference and message the delegate object with a method such as this:

- (void)logEventWithFormat:(NSString *)format, ... {
    va_list argList;
    id del = self.delegate;
    if (del != nil && 
        [del conformsToProtocol:@protocol(AProtocolWithOptionalMethods)] &&
        [del respondsToSelector:@selector(logEventWithFormat:)])
    {
        // Perform selector on object 'del' with 'argList'
    }
}

我假设这是不可能的,因此 Foundation 框架中的类似方法声明 - 在 NSString 中:

I am assuming this is not possible, hence the similar method declaration in the Foundation framework - in NSString:

- (id)initWithFormat:(NSString*)format, ...;

- (id)initWithFormat:(NSString *)format arguments:(va_list)argList;

我假设我希望委托给的协议应该建议实施:

I assume that the protocol I wish to delegate to should suggest the implementation of:

- (void)logEventWithFormat:(NSString *)format arguments:(va_list)argList;

所以我选择器 @selector(logEventWithFormat:arguments:) 可以用于调用:

so I the selector @selector(logEventWithFormat:arguments:) can be used an called with:

[del performSelector:@selector(logEventWithFormat:arguments:) 
          withObject:format
          withObject:argList];

我只是想知道我是否遗漏了什么或为了实现我的目标而走了很长一段路?

I just wondered if I was missing something or going the long way around to achieve what I'm trying to?

推荐答案

你可以将任何你想要的东西传递给运行时函数 objc_msgSend.

You can pass anything you want into the runtime function objc_msgSend.

objc_msgSend(del, @selector(logEventWithFormat:arguments:), format, argList);

这是发送手动构建的消息的最强大的方式.

It's the most powerful way of sending a manually constructed message.

但是,不清楚您是否需要以这种方式执行调用.正如 KennyTM 指出的那样,在您拥有的代码中,您可以直接调用该方法.

However, it's not clear that you need to perform the invocation this way. As KennyTM pointed out, in the code you have, you could invoke the method directly.

这篇关于Objective-C va_list 和选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆