使用“performSelector”返回非 id 结果

发布于 2024-12-19 11:42:44 字数 780 浏览 1 评论 0原文

出于调试目的,我需要从一段代码调用 CGFloat 访问器方法,该代码根据 iVar 的名称生成选择器;

- (CGFloat) myIVar {
    return myIVar;
}

setter 具有以下形式;

- (void) setMyIVar: (CGFloat) p_myIVar {
    [self willChangeValueForKey: @"myIVar"];
    myIVar = p_myIVar;
    [self didChangeValueForKey: @"myIVar"];
}

为了跟踪回调,我在“observeValueForKeyPath...”代码的“didChange”部分放置了一个调试部分,并且我想调用 getter 访问器来打印结果;

SEL genericGetter = NSSelectorFromString (p_keyPath);  // i.e. '[self myIVar]'
NSLog (@"Key: %@ changed to %3.6f", p_keyPath, [self performSelector: genericGetter]);

问题是“perormSelector”返回一个无法转换为 CGFloat 的 id。另外,Apple 的文档提供了 3 个关于 PerformSelector 的示例,所有这些示例都返回 id,但它们没有告诉您如何处理非 id 结果。

谁能告诉我如何实现我想要使用的逻辑? 非常感谢,VV。

For debuging purposes, I need to call a CGFloat accessor method from a piece of code that generates a selector from the name of the iVar as per;

- (CGFloat) myIVar {
    return myIVar;
}

The setter has the form;

- (void) setMyIVar: (CGFloat) p_myIVar {
    [self willChangeValueForKey: @"myIVar"];
    myIVar = p_myIVar;
    [self didChangeValueForKey: @"myIVar"];
}

So that I can follow the trail of callbacks, I've put a debug section in the 'didChange' part of the 'observeValueForKeyPath...' code and I want to call the getter accessor to print out the result thus;

SEL genericGetter = NSSelectorFromString (p_keyPath);  // i.e. '[self myIVar]'
NSLog (@"Key: %@ changed to %3.6f", p_keyPath, [self performSelector: genericGetter]);

The problem is that 'perormSelector' returns an id which can't be cast to a CGFloat. Also, Apple's documentation gives 3 examples on performSelector all of which return ids but they don't tell you what to do for non-id results.

Can anyone tell me how to implement the logic I am tring to use please?
Many thanks in advance, VV.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾铮苏瑾 2024-12-26 11:42:44

您可以使用 valueForKey 免费获得包装:

再次,考虑到:

- (CGFloat) myIVar {
    return myIVar;
}

像这样的东西会起作用:

id *value = [self valueForKey:@"myIVar"];
// if myIVar is a float, then value will be of type NSNumber
// if myIVar were an NSString, then value will be an NSString

如果您所做的只是记录这个,那么您可以直接记录“value”。如果我正确理解您的需求,这应该比您现在所做的更简单。

You can get the wrapping for free using valueForKey:

Again, given this:

- (CGFloat) myIVar {
    return myIVar;
}

Something like this will work:

id *value = [self valueForKey:@"myIVar"];
// if myIVar is a float, then value will be of type NSNumber
// if myIVar were an NSString, then value will be an NSString

And if all you are doing is logging this, then you can log 'value' directly. If I'm understanding your need correctly, this should be simpler than what you are doing now.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文