【问题标题】:NSDictionary literals causing crash when used with setTitleTextAttributes与 setTitleTextAttributes 一起使用时导致崩溃的 NSDictionary 文字
【发布时间】:2013-04-19 14:47:47
【问题描述】:

我正在将我的 xcode 项目转换为现代目标 c。在我的 AppDelegate 中,以前,我有这个代码:

- (void)customizeAppearance
{
    [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:barButtonFont, UITextAttributeFont, nil] forState:UIControlStateNormal];
}

以下是使用@{keys : value} 创建NSDictionary 的字面方法,我将其更改为:

[[UIBarButtonItem appearance] setTitleTextAttributes:@{UITextAttributeFont: barButtonFont} forState:UIControlStateNormal];

这一更改使我的系统崩溃。错误输出为:

* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: 尝试插入 nil 对象 对象[0]'

有谁知道为什么以及我可以做些什么来解决它?

我可以忽略它,但稍后它会咬我,因为我会忘记。我确实想将我的整个项目更改为现代目标 c,并且将来不必记住为什么一个代码不是“现代”的。

谢谢。

【问题讨论】:

  • 我猜你的barButtonFontnil
  • UIFont *barButtonFont = [UIFont fontWithName:@"Helvetica CE" size:12.0];
  • 您的代码确实返回 nil。使用此代码[UIFont systemFontOfSize:12.0] 获取 Helvetica 字体。
  • 默认是 Helvetica 吗?

标签: objective-c literals


【解决方案1】:

问题在于barButtonFontnil,(可能是因为您没有可用的名为Helvetica CE 的字体)。这个问题只有在你转向文字语法时才会暴露出来,因为“在容器中键和值都不能有值 nil。如果编译器可以在编译时证明键或值是 nil,那么将发出警告。否则会出现运行时错误。”

这里有更多细节:http://clang.llvm.org/docs/ObjectiveCLiterals.html

【讨论】:

    【解决方案2】:

    要设置属性,您需要为两种状态设置它。

    试试这个sn-p的代码:

     NSDictionary* textAttributes = [NSDictionary dictionaryWithObject: [UIFont fontWithName:@"Helvetica" size:45.0] forKey: UITextAttributeFont];
    
    [[UIBarButtonItem appearance] setTitleTextAttributes: textAttributes
                                                forState: UIControlStateDisabled];
    
    [[UIBarButtonItem appearance] setTitleTextAttributes: textAttributes
                                                forState: UIControlStateNormal];
    

    在 Appdelegate 中实现这个

    有关更多详细信息,您也可以参考此答案。

    UIBarButtonItem appearance setTitleTextAttributes does not affects UIControlStateDisabled state

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多