NSMutableOrderedSet removeObjectAtIndex方法执行不稳定问题求助
NSMutableOrderedSet 删除条目行为不一致问题
尝试从NSMutableOrderedSet中删除条目时,removeObjectAtIndex:方法执行行为不稳定,有时生效有时无效,相关代码及调试信息如下:
相关代码
NSMutableOrderedSet* detailPlaylist; [detailPlaylist removeObjectAtIndex:indexPath.row];
调试信息
删除操作前
(lldb) po [detailPlaylist objectAtIndex:0] { videoDuration = "5:15"; videoId = "i-bu47QpWWc"; videoSelected = n; videoThumbnailData = {length = 10595, bytes = 0xffd8ffe0 00104a46 49460001 01000001 ... 84200421 0801ffd9 }; videoThumbnailUrl = "https://i.ytimg.com/vi/i-bu47QpWWc/hqdefault.jpg?sqp=-oaymwEiCKgBEF5IWvKriqkDFQgBFQAAAAAYASUAAMhCPQCAokN4AQ==&rs=AOn4CLDbkeqgCWR4RSyTpUhI9IM2Gd2poA"; videoTitle = "张惠妹 A-Mei - 站在高岗上 官方MV (Official Music Video)"; } (lldb) po detailPlaylist.count 1
删除操作后
(lldb) po detailPlaylist.count 1 (lldb) po [detailPlaylist objectAtIndex:0] error: warning: couldn't get cmd pointer (substituting NULL): no variable named '_cmd' found in this frame error: Execution was interrupted, reason: internal ObjC exception breakpoint(-7).. The process has been returned to the state before expression evaluation.
问题分析
从调试信息看,删除操作后集合的count仍为1,但访问索引0时触发内部异常,说明集合内部结构已损坏,大概率是以下原因:
- 多线程竞争:NSMutableOrderedSet并非线程安全类,若同时在多个线程对其进行读写操作,会破坏内部数据结构,导致这种诡异的状态。
- 野指针/生命周期问题:
detailPlaylist可能未被正确初始化,或在操作过程中被意外释放、重新赋值,导致删除操作未作用在目标实例上。 - 索引合法性问题:若
indexPath.row超出集合当前元素数量范围,会触发未定义行为,但此场景下删除前count为1,若索引为0则不存在该问题,需确认索引值是否正确。
解决方案
- 保证线程安全:如果涉及多线程操作,用串行队列或锁(如
@synchronized、NSLock)包裹所有对该NSMutableOrderedSet的读写操作,避免并发访问。 - 校验实例有效性:确认
detailPlaylist已通过[[NSMutableOrderedSet alloc] init]或其他合法方式初始化,且在操作时未被释放或篡改。 - 操作前校验索引:调用
removeObjectAtIndex:前,先判断indexPath.row < detailPlaylist.count,避免索引越界引发的潜在问题。
内容的提问来源于stack exchange,提问作者Rao
相关产品推荐
相关产品推荐

