iOS 4.3 中的 UIFont exc_bad_access 错误
我使用 fontWithSize:
方法设置标签的字体属性,虽然它在 iOS 5、iOS 4.3 中工作正常,但我收到 exc_bad_access 错误。这是我的代码:
UILabel *headerText = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width - 10, 42)];
headerText.text = [tableView.dataSource tableView:tableView titleForHeaderInSection:section];
headerText.font = [[UIFont alloc] fontWithSize:8];
同样,这段代码在 iOS 5 中完美运行,但在 4.3 中的最后一行崩溃了。我检查了 Apple API 文档,fontWithSize:
以及 UILabel
的字体属性自 iOS 2 以来就已存在。这里还有其他问题吗?
I am setting the font property of a label using the fontWithSize:
method and while it works fine in iOS 5, iOS 4.3 I am getting an exc_bad_access error. Here is my code:
UILabel *headerText = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width - 10, 42)];
headerText.text = [tableView.dataSource tableView:tableView titleForHeaderInSection:section];
headerText.font = [[UIFont alloc] fontWithSize:8];
Again, this code works perfectly in iOS 5, but crashes as the last line in 4.3. I checked the Apple API docs and fontWithSize:
as well as the font property of a UILabel
have both been around since iOS 2. Is there anything else wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试调用从未初始化的对象上的方法。具体来说,您的行
正在
分配
一个新的字体对象,但从未初始化它。对-fontWithSize:
的后续调用会崩溃,因为它假定该对象已初始化。您想创建什么字体?由于您跳过了初始化程序,因此您从未提供字体系列。当然,UIFont 甚至没有公开一个好的初始化程序(您可以调用
-init
但无法提供字体系列)。这表明您应该使用类“便利”方法来构造字体,例如+[UIFont fontWithName:size]
或+[UIFont systemFontOfSize:]
。在你的情况下,我假设你想要后者,所以你应该使用You're trying to call methods on an object that was never initialized. Specifically, your line
is
alloc
ing a new font object, but then never initializing it. The subsequent call to-fontWithSize:
is crashing because it assumes the object has been initialized.What font were you trying to create? Since you skipped the initializer, you never provided a font family. Of course, UIFont doesn't even expose a good initializer (you could call
-init
but there's no way to provide the font family). This is an indication that you're supposed to use the class "convenience" methods to construct your font, e.g.+[UIFont fontWithName:size]
or+[UIFont systemFontOfSize:]
. In your case I'm assuming you want the latter, so you should use如果使用 alloc 来初始化,该方法通常以
init
开头。fontWithSize :
不用于首字母。这意味着您应该使用现有的字体实例来调用它。
例如:
但如果要初始化一个实例,则需要调用以init开头的类方法或实例方法。
If you use alloc to initial, the method usually begins with
init
.fontWithSize :
is not used to initial.It means that you should call it using an existing font instance.
For example:
But if you want to initial an instance, you need call the class method or instance method beginning with init.
fontWithSize
是一个类方法而不是实例方法,基本上你不分配 UIFont 对象,你只需调用
[UIFont fontWithSize:8]
fontWithSize
is a class method not an instance methodbasically you dont allocate a UIFont object, you just call
[UIFont fontWithSize:8]