You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

初始化空NSMutableAttributedString时崩溃问题求助

问题分析:Xcode 14 Playground创建空NSMutableAttributedString崩溃

问题描述

在未关联项目的全新Playground中执行以下代码时触发崩溃:

import Foundation

let str = NSMutableAttributedString()

崩溃栈信息如下:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x1bb4d7d84)
  * frame #0: 0x00000001bb4d7d84 AppKit`-[NSApplication _crashOnException:] + 324
    frame #1: 0x00000001bb4d7a9c AppKit`-[NSApplication reportException:] + 580
    frame #2: 0x00000001bb581fb4 AppKit`uncaughtErrorProc + 156
    frame #3: 0x00000001b87010bc CoreFoundation`__handleUncaughtException + 800
    frame #4: 0x00000001b83c8314 libobjc.A.dylib`_objc_terminate() + 132
    frame #5: 0x00000001b84e1ea4 libc++abi.dylib`std::__terminate(void (*)()) + 20
    frame #6: 0x00000001b84e4c1c libc++abi.dylib`__cxxabiv1::failed_throw(__cxxabiv1::__cxa_exception*) + 36
    frame #7: 0x00000001b84e4bc8 libc++abi.dylib`__cxa_throw + 140
    frame #8: 0x00000001b83bff6c libobjc.A.dylib`objc_exception_throw + 420
    frame #9: 0x00000001b94e4718 Foundation`-[NSRLEArray objectAtIndex:effectiveRange:] + 188
    frame #10: 0x00000001b94f70fc Foundation`-[NSConcreteMutableAttributedString attribute:atIndex:effectiveRange:] + 52
    frame #11: 0x0000000108e76a78 PlaygroundLogger`___lldb_unnamed_symbol752 + 80
    frame #12: 0x0000000108e76c7c PlaygroundLogger`___lldb_unnamed_symbol756 + 20
    frame #13: 0x0000000108e73510 PlaygroundLogger`___lldb_unnamed_symbol614 + 60
    frame #14: 0x0000000108e73960 PlaygroundLogger`___lldb_unnamed_symbol627 + 20
    frame #15: 0x0000000108e6e98c PlaygroundLogger`___lldb_unnamed_symbol487 + 432
    frame #16: 0x0000000108e7450c PlaygroundLogger`___lldb_unnamed_symbol655 + 376
    frame #17: 0x0000000108e6d864 PlaygroundLogger`playground_log_hidden + 260
    frame #18: 0x000000010463434c $__lldb_expr26`main at MyPlayground6.playground:3:5
    frame #19: 0x00000001042863d8

已排除Playground扩展干扰,升级至Xcode 14后出现该问题,重启Xcode及电脑无效。

原因分析

从崩溃栈可定位到问题根源:

  1. Playground的日志系统在尝试输出空NSMutableAttributedString实例时,调用了-[NSConcreteMutableAttributedString attribute:atIndex:effectiveRange:]方法
  2. 该方法内部访问NSRLEArray的索引0,但空富文本字符串无任何内容,直接触发数组越界异常,最终导致崩溃。

这是Xcode 14 Playground的已知bug,空NSMutableAttributedString无法被日志系统正确处理。

解决方法

  • 避免创建完全空的NSMutableAttributedString,初始化时传入空字符串即可修复:
import Foundation

let str = NSMutableAttributedString(string: "")
  • 升级Xcode至修复该bug的后续版本(如Xcode 14.1及以上)。

内容的提问来源于stack exchange,提问作者Peter R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:01:16