Teaching Your Database New Tricks

Databases are great for storing simple data types. Create a table with a few string fields, a data field, and a longer text field and you have the basics of a blog. But what if you wanted to store something more complicated, like an image?

To do that we’ll have to store the raw data in a blob (or in the case of our iOS/OSX apps, an NSData field) and reconstitute it later when we need it.

For our example, we will do just that. Store the data for an image in an NSData field on a table in the database and create a UIImage out of that data when we need to use it. We’ll be using Swift in our examples but the principals still apply in other languages.

We start by simply creating the NSData field on the table.

class MyTable {
  dynamic var imageData: NSData
}

Now we can create the swift calculated property.

class MyTable {
  dynamic var imageData: NSData
  var image: UIImage? {
    get {
      ...
    }
    set(newImage) {
      ...
    }
  }
}

The implementation of our getter is pretty straight forward. We take the raw data and pass it to the appropriate initializer. In our case, we pass it to UIImage(data: NSData) which will return an Optional depending on whether or not it was able to create an image.

get {
  return UIImage(data: imageData)
}

The implementation of our setter requires us to change our object into NSData in order to be stored. For UIImage, we can use UIImagePNGRepresentation() which returns an NSData variable.

set(newImage) {
  imageData = UIImagePNGRepresentation(newImage)
}

The same process can be applied to any complex data type that isn’t natively supported by your database. The only thing that is required is the ability to marshal the object into something that can be stored by the database.

Photo of Tim Bugai

Programming since the age of 8, Tim has a strong background in agile software development, Ruby, JavaScript, and iOS. He’s also helping our team with mobile application development, often leading the charge.

Comments

Add a Comment

Hmm...that didn't work.

Something went wrong while adding your comment. If you don't mind, please try submitting it again.

Comment Added!

Your comment has been added to this post. Please refresh this page to view it.

Optional. If added, we will display a link to the website in your comment.
Optional. Never shared or displayed in your comment.
  1. August 23, 2015 at 16:45 PM

    Thanks for the tutorial. I have been trying to save the image location in my Realm database so it could be loaded later from its preexisting location on an iOS device. Next task is to see if I can scale the image prior to storage. The largest image needs to be is 200px wide.