Debugging Tip: Saving NSData to a File

Saving NSData when debugging is easier to do now for specific data types but helpful to know how to do in general. Xcode 5.1 introduced graphical Quick Looks for variables a long time ago, but I hadn’t experimented with that until today. I’ll talk about it below, but first the old way of doing things…

It’s easy to save a chunk of NSData to a file from the debugger, and it can be really helpful when debugging. Here’s an example I encountered when chatting with another Smile engineer yesterday. We were discussing a method which returns a UIImage. We were seeing an artifact in the image, and we wanted to determine the origin of that artifact. We fired up the app in the Simulator and put a breakpoint at the end of the method which generates the UIImage. Then, we did this in the Debugger.

p [UIImagePNGRepresentation(keyBackgroundImage) writeToFile:[NSTemporaryDirectory()
	 stringByAppendingPathComponent:@"image.png"] atomically:NO]
po NSTemporaryDirectory()

The first line writes the data to a file (in the guise of printing the result of the writeToFile:atomically: method). The second line tells you the path of the folder in which the “image.png” file is saved. It’s handy to use NSTemporaryDirectory() because that works easily for sandboxed applications on macOS.

It was easy to open the resulting image file in Acorn (for me) and Photoshop (for the other engineer) to verify that the background image was not the source of the artifact.

Xcode’s graphical Quick Look for variables obviates this technique for images. All you need to do is:

  1. Hover over the variable name in your source code
  2. Click the Quick Look icon
  3. Click the Open button to open your file in its default file viewer

Xcode showing Quick Look variable view

This also works well for small amounts of proprietary NSData, as Xcode includes a Quick Look viewer to show 512 byte pages in HexFiend style. If you’re looking for something at the 100,000 byte mark, you’ll really want to save off the data and open it with HexFiend. In that case, it’s handy to know the above technique as well.

You can also write your own Quick Look display for your custom types, as Apple notes. I suspect that’s overkill in many cases.

I don’t claim to have originated this technique. I’d love to give credit (or a beer) to whomever I learned it from, but I simply don’t recall. I wouldn’t have posted about it, but for the fact that it was new to the engineer with whom I discussed it. Therefore I figure it’s worth a post after all. Hopefully, it will prove helpful to someone trying to extract NSData to a file while debugging.