Core Data and NSAttributedString

I’m currently creating an app that uses some weird formatting and inline images that can be handled nicely by NSAttributedString.

The app is bundled with a pre-populated database and I was considering populating the database with the already formatted strings and images.

Core Data supports NSAttributedStrings—just set the attribute to be Transformable and you can create and store attributed strings along with most attributes.

The interesting thing is that it can also store images within the strings if you add it using NSTextAttachment:

let attributedString = NSMutableAttributedString(string: "Hello images!")
var attributes: [String : AnyObject]?

if let font = UIFont(name: "AvenirNextCondensed-Medium", size: 30) {
    attributes = [ NSFontAttributeName : font ]
}

let range = NSRange(location: 0, length: attributedString.length)
attributedString.setAttributes(attributes, range:range )

// You can safely pass nil to both parameters if using an image
let textAttachment = NSTextAttachment(data: nil, ofType: nil) 
textAttachment.image = UIImage(named: "TestImage")        
let imageString = NSAttributedString(attachment: textAttachment)
attributedString.appendAttributedString(imageString)

coreDataEntity.transformableAttribute = attributedString

There’s a few issues with this:

  1. Your database will get big fast. Unlike the Binary attribute, there’s no way to tell Core Data to use external storage.
  2. You’re passing in the scale of image of the device that created the image. For example, if you’re running the app on an iPhone 6, then UIImage(named:) will return an @2x image and this and only this scale is what will be stored in the database

This will be fine if it’s going to be accessed on the same device that it’s created on, but if you use any sort of syncing or you want to deliver a pre-populated database in your app bundle, then you’re going to be passing around an image that might be the wrong scale for the device.

Also, storing attributed strings this way breaks any connection with dynamic text styles, so there’s no resizing of the string after it comes out of the database if the user changes the text size in Accessibility. This makes sense as the font is hardcoded into the attributed string so there’s no way of the system knowing that it should resize it, but it does make storing attributed strings in the database less useful if you want to provide dynamic text resizing (which you should).

Because of these limitations, I think I’m going to stick with formatting the strings and adding the image on the fly for the moment, but it’s good to know what’s possible with Core Data.