# What’s the recommended way to memory-map a file?

**URL:** <https://forums.swift.org/t/what-s-the-recommended-way-to-memory-map-a-file/19113>\
**Category:** Using Swift\
**Created:** [December 28, 2018, 2:31am UTC](https://forums.swift.org/t/what-s-the-recommended-way-to-memory-map-a-file/19113 "2018-12-28T02:31:38Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![benrimmington](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/benrimmington/32/695_2.png) [@benrimmington](https://forums.swift.org/u/benrimmington)\
**Post date:** [December 28, 2018, 1:32pm UTC](https://forums.swift.org/t/what-s-the-recommended-way-to-memory-map-a-file/19113/5 "2018-12-28T13:32:16Z")

</div>

[`Data.ReadingOptions`](https://developer.apple.com/documentation/foundation/nsdata/readingoptions) are documented as _hints_ only, so there shouldn't be an error.

`.alwaysMapped` versus `.mappedIfSafe` is described in the [Foundation Release Notes](https://developer.apple.com/library/archive/releasenotes/Foundation/RN-Foundation-iOS/Foundation_iOS5.html):

> **Safe File Mapping for NSData**
> 
> Before iOS 5, specifying NSDataReadingMapped (or NSMappedRead) for -initWithContentsOfFile:options:error: would cause NSData to always attempt to map in the specified file. However, in some situations, mapping a file can be dangerous. For example, when NSData maps a file from a USB device or over the network the existence of said file can't be guaranteed for the lifetime of the object. Accessing the NSData's bytes after the mapped file disappears will likely cause unpredictable crashes in your application.
> 
> For applications linked on iOS 5 or later, NSDataReadingMapped will now only map the requested file if it can determine that mapping the file will be relatively safe. To reflect this change, NSDataReadingMapped has been deprecated and is now an alias for NSDataReadingMappedIfSafe.
> 
> The methods -dataWithContentsOfMappedFile: and -initWithContentsOfMappedFile: have been deprecated. In the very rare event that your application needs to map a file regardless of safety, you may use the NSDataReadingMappedAlways option.

---

_[View the full topic](https://forums.swift.org/t/what-s-the-recommended-way-to-memory-map-a-file/19113)._
