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.
Comments
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.