代码之家  ›  专栏  ›  技术社区  ›  JoBu1324

PerformSelector的结果:与标准点标记调用不同?

  •  1
  • JoBu1324  · 技术社区  · 17 年前

    最近我的代码中出现了一些意想不到的编译错误,这让我很困惑。我做了一些故障排除,我想出了一个测试代码:

    1 float performSelectorResult, messageResult;
    2 SEL selector = @selector(smallContentCellMargin);
    3
    4 NSLog (@"selector %s result %f", selector,  [defaults performSelector:selector]);
    5 NSLog (@"message result is %f", defaults.smallContentCellMargin);
    6
    7 performSelectorResult = [defaults performSelector:selector];
    8 messageResult = defaults.smallContentCellMargin;
    

    如果按原样运行代码,我会在第7行得到一个编译错误:“分配中的类型不兼容”。但是,如果我注释掉第7行,代码构建和运行;nslog中的结果是:

    2009-07-21 18:31:44.823 ICE[24347:20b] selector smallContentCellMargin result 0.000000
    2009-07-21 18:31:44.830 ICE[24347:20b] message result is 7.000000
    

    我使用了非常相似的代码来检索uifont,但从未使用float。有什么我不知道的吗,或者这是Objective-C中的错误吗?我很困惑。

    1 回复  |  直到 17 年前
        1
  •  3
  •   Jim Correia    17 年前

    首先,在使用nslog进行日志记录时,您将选择器视为字符串。不要这样做-SEL不是字符串。使用%@格式和nsstringfromselector(选择器)。

    对于非对象返回值,应使用nsinvocation或-valueforkey:。在后一种情况下,您将得到一个浮动框作为一个nsnumber。