Re: Crash in dragImageForSelection


Ben Kennedy
 

On 26 Apr 2019, at 4:26 am, John Brownie <john_brownie@...> wrote:

I have what seems to be a simple operation to perform, but it crashes. I have a custom view which includes an NSTextView called textView. In the mouseDragged(with:) function in my view subclass, I have the following code (leaving out the logic deciding whether it is appropriate as a drag source):

textView?.setSelectedRange(NSMakeRange(0, textView!.textStorage!.length))
let dragImage = textView?.dragImageForSelection(with: event, origin: nil)
I don't have any useful help for you, but a couple of things struck me as odd about this.

First of all, you're treating textView as an optional sometimes, and force-unwrapping it elsewhere. Prefacing the whole block with a `guard` or `if let` would clean this up.

More on topic, I looked up the documentation for `setSelectedRange()`, and it is strange:

https://developer.apple.com/documentation/appkit/nstextview/1449256-setselectedrange?language=objc

charRange: A non-nil, non-empty array of objects responding to the NSValue rangeValue method. The ranges in the ranges array must begin and end on glyph boundaries and not split base glyphs and their nonspacing marks.
The method clearly takes an NSRange argument, but the documentation instead talks about an array of NSValue objects. WTH? I guess this is a documentation error? (Somebody file a radar... crickets)

If you call `selectedRange` immediately after `setSelectionRange(…)`, does it reflect the range you tried to set?

b

Join {cocoa@apple-dev.groups.io to automatically receive all group messages.