In order to break another problem down into smaller parts, I am trying to set up all the TextKit components. However, I am getting an crash after changing how I initialize NSTextStorage. For testing purposes I have simplified the project to the following:
import UIKit
class ViewController3: UIViewController {
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var myTextView: MyTextView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let container = NSTextContainer(size: myTextView.bounds.size)
        let layoutManager = NSLayoutManager()
        let textStorage = NSTextStorage(string: "This is a test")
        layoutManager.addTextContainer(container)
        //layoutManager.textStorage = textView.textStorage  // This works
        layoutManager.textStorage = textStorage  // This doesn't work
        myTextView.layoutManager = layoutManager
    }
}
class MyTextView: UIView {
    var layoutManager: NSLayoutManager?
    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext();
        // Enumerate all the line fragments in the text
        layoutManager?.enumerateLineFragmentsForGlyphRange(NSMakeRange(0, layoutManager!.numberOfGlyphs), usingBlock: {
            (lineRect: CGRect, usedRect: CGRect, textContainer: NSTextContainer!, glyphRange: NSRange, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
            // Draw the line fragment
            self.layoutManager?.drawGlyphsForGlyphRange(glyphRange, atPoint: CGPointMake(0, 0))
        })
    }
}
It crashes at enumerateLineFragmentsForGlyphRange with an exception code of EXC_I386_GPFLT. That code isn't very explanitory. The basic problem seems to be coming down to how I am initializing NSTextStorage.
If I replace
let textStorage = NSTextStorage(string: "This is a test")
layoutManager.textStorage = textStorage
with this
layoutManager.textStorage = textView.textStorage
then it works. What am I doing wrong?
 
     
    