菜鸟教程小白 发表于 2022-12-11 17:51:45

ios - NSData.write 在 iOS 8 上触发 ECX_BAD_ACCESS


                                            <p><p>我的应用程序显示 OpenStreetMap 切片(256*256 图像),并在用户浏览 map 时将它们缓存在磁盘上。</p>

<p>在 iOS 10 上,一切都很好,但在 iOS 8 上,如果我不以原子方式编写 NSData,应用程序会崩溃 (EXC_BAD_ACCESS)。以原子方式执行它没有问题,但我想了解发生了什么。</p>

<p>这是我正在使用的相关代码:</p>

<pre><code>private func putInCache(key:NSString, data:NSData) {

    // Get the path:
    let path:String = &#34;\(self.imagesFolderPath)/\(key)&#34;;
    var success:Bool = false;

    // Save the image, if it does not exists:
    if(!FileManager.default.fileExists(atPath:path)) {

      // Run in background:
      DispatchQueue.global().async {

            // Put the image in the memory cache:
            self.memoryCache.setObject(data, forKey:key);

            // Insert the row in the database:
            let success = insertDataInDb(...);

            // Then save the file (if the DB insertion succeeded):
            if(success) {

                data.write(toFile:path, atomically:false); // If I set atomically to true, it works.
            }
      }
    }
}
</code></pre>

<p>有人知道为什么以原子方式写入数据之间存在差异吗?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>来自 Apple 文档 (<a href="https://developer.apple.com/reference/foundation/nsdata" rel="noreferrer noopener nofollow">https://developer.apple.com/reference/foundation/nsdata</a>):</p>

<blockquote>
<p>Atomic writes guarantee that the data is either saved in its entirety,
or it fails completely. The atomic write begins by writing the data to
a temporary file. If this write succeeds, then the method moves the
temporary file to its final location.</p>
</blockquote>

<p>您可能会遇到崩溃,因为不同队列同时尝试写入同一路径。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - NSData.write 在 iOS 8 上触发 ECX_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40090845/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40090845/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - NSData.write 在 iOS 8 上触发 ECX_BAD_ACCESS