iOS11上UILabel.setAttributedText的兼容性问题

前言

今天发现一处只在iOS11上出现的崩溃.出现在下面这个代码片段.

    self.testLabel.attributedText = @"";
    self.testLabel.text = @"123";
    [self.testLabel sizeToFit];

这样的写法当然不对,赋值attributedText的类型错误了.
不过为什么iOS11之前没有崩溃,在iOS11上崩了?
写了demo,用几种不同的写法,分别在10.3与11.0系统上试了一下.

iOS 10.3

- (void)addTestLabel
{
    self.testLabel = [[UILabel alloc] init];
    self.testLabel.attributedText = @"";
//    self.testLabel.text = @"123";
    [self.testLabel sizeToFit];
    [self.view addSubview:self.testLabel];
}

此种写法会崩溃.
sizeToFit时,因为text无合法值,试图取attributedText的文本,调用了[attributedText string]接口.

CDCB6254-5B6E-4AA1-A6FE-9BE5EB90D065.png
- (void)addTestLabel
{
    self.testLabel = [[TestLabel alloc] init];
    self.testLabel.text = @"123";
    self.testLabel.attributedText = @"";
    [self.testLabel sizeToFit];
    [self.view addSubview:self.testLabel];
}

此种写法会崩溃.
text设置合法值时,内部对attributedText做了对应赋值.外部再次设置attributedText触发了比对逻辑,对非法值调用了[attributedText string]接口.造成崩溃.

51C0AFB1-2465-463C-ABFF-08461906A43D.png
1B8DCF09-3B7B-4B4F-844E-0F91AAAB7FAD.png
- (void)addTestLabel
{
    self.testLabel = [[UILabel alloc] init];
    self.testLabel.attributedText = @"";
    self.testLabel.text = @"123";
    [self.testLabel sizeToFit];
    [self.view addSubview:self.testLabel];
}

此种写法不会崩溃.根据上面的经验看来,应该是路径上的逻辑没有调用到[attributedText string].

iOS 11

10.3上该崩溃的,在11上还是会崩.
所以直接调试10.3上不会崩溃的那段代码,结果确实是崩了.
从崩溃调用栈可以发现,iOS11在setText时,增加了与attributedText的比对逻辑,调用到[attributedText string]造成了崩溃.原因就在这里.

- (void)addTestLabel
{
    self.testLabel = [[UILabel alloc] init];
    self.testLabel.attributedText = @"";
    self.testLabel.text = @"123";
    [self.testLabel sizeToFit];
    [self.view addSubview:self.testLabel];
}
130CDBF6-7A1A-4AF2-8EEC-0D92A751BE84.png

后记

这样的崩溃比较不应该,因为编译时就有类型转换错误的警告,因为没有及时解决,结果在新系统上踩了个大坑~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,185评论 6 13
  • 1.badgeVaule气泡提示 2.git终端命令方法> pwd查看全部 >cd>ls >之后桌面找到文件夹内容...
    i得深刻方得S阅读 4,770评论 1 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,992评论 19 139
  • 雨后的麦田 松软的像棉花一样 我要去看一眼从前 走着小时候走过的路 摘几颗红枣 还是那时的味道 坡边的小野菊开的正...
    枺一文字阅读 388评论 2 5
  • 每一個,你決定接受與你親近的人,請同時做好隨時與你疏離的準備。 我遇到過很多人,形形色色。遇到,不代表...
    TurpinHero阅读 126评论 0 0