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

程序在iPhone X/8+正常旧机型报错,attributesOfItem仅部分模拟器抛异常

Hey there, let's break down and fix the issue you're facing step by step!

Problem Breakdown

Your app runs smoothly on iPhone X and 8+, but crashes on older devices with a NSCocoaErrorDomain Code=260 error — this means your code is trying to access file.txt in the Documents directory, but the file doesn't exist there. On top of that, attributesOfItem(atPath:) throws exceptions only on some simulator instances, which ties back to the same root cause: inconsistent file presence across different device environments.

Likely Causes
  • Missing file in older device/simulator sandboxes: Each simulator instance has its own isolated sandbox, so if you manually added file.txt to some simulators but not others, you'll hit this error. For older physical devices, the file might not have been copied over correctly during deployment.
  • Unsafe use of try!: Using try! forces the runtime to crash if any error occurs. File operations are inherently risky (files can go missing, permissions can change), so this fragile approach breaks as soon as the file isn't where you expect.
  • iOS version API differences: While attributesOfItem(atPath:) is widely compatible, older iOS versions might handle file path resolution or permissions slightly differently, making the missing file issue more prominent.
Fixes & Recommendations

1. Replace try! with Safe Error Handling

First, eliminate the immediate crash by ditching try! and using proper do-catch error handling. This lets you gracefully handle missing files instead of crashing:

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsDirectory.appendingPathComponent("file.txt")

do {
    let fileAttributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
    // Proceed with your logic using the attributes
} catch let error {
    print("Failed to access file attributes: \(error.localizedDescription)")
    // Add fallback logic here (e.g., create the file, notify the user)
}

2. Ensure the File Exists Before Accessing It

Before trying to read or get attributes for file.txt, check if it exists. If not, create it or copy it from your app bundle (if the file is part of your project):

func ensureFileExists() {
    let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let targetFileURL = documentsDir.appendingPathComponent("file.txt")
    
    guard !FileManager.default.fileExists(atPath: targetFileURL.path) else { return }
    
    // Option 1: Create an empty file if it doesn't exist
    do {
        try Data().write(to: targetFileURL)
        print("Empty file created successfully")
    } catch {
        print("Failed to create file: \(error)")
    }
    
    // Option 2: Copy the file from your app bundle (if you included it in your project)
    if let bundleFileURL = Bundle.main.url(forResource: "file.txt", withExtension: nil) {
        do {
            try FileManager.default.copyItem(at: bundleFileURL, to: targetFileURL)
            print("File copied from bundle to Documents")
        } catch {
            print("Failed to copy file from bundle: \(error)")
        }
    }
}

Call this function early in your app's lifecycle (like in application(_:didFinishLaunchingWithOptions:) or the init of your main view controller) to ensure the file is present before any operations.

3. Standardize Simulator Testing

To avoid inconsistencies across simulator instances:

  • Add file.txt to your project's Copy Bundle Resources build phase (so it's included in every app build)
  • Use the bundle copy logic above to automatically populate the Documents directory on first launch for every simulator/device

4. Verify iOS Version Compatibility

Double-check that all file-related APIs you're using are supported on your target iOS version. If you hit version-specific issues, use conditional checks:

if #available(iOS 11.0, *) {
    // Use iOS 11+ specific file logic
} else {
    // Fallback for older iOS versions
}
Final Notes

The root issue is that file.txt isn't consistently present across all devices/simulators, and your use of try! turns this missing file into a fatal crash. By adding safe error handling and ensuring the file exists upfront, you'll fix the crashes on older devices and inconsistent simulator behavior.

内容的提问来源于stack exchange,提问作者Shaa'ban Mego

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:32:22