Search code examples
swiftcocoanseventnsresponder

UnsafeMutablePointer<Void> to [NSObject : AnyObject]


I am overriding NSResponder’s mouseEntered(theEvent: NSEvent) method and want to retrieve the value I set when creating a NSTrackingArea in Swift. I am using this constructor to create the NSTrackingArea and pass the following object as userInfo.

let trackerData = ["myTrackerKey": view]
let trackingArea = NSTrackingArea(rect: trackingRect, options: [.EnabledDuringMouseDrag, .MouseEnteredAndExited, .ActiveInActiveApp], owner: self, userInfo: trackerData)

(view : NSView as well as trackingRect : NSRect do exist)

I am setting trackerData as userInfo so I can read it later in mouseEntered(theEvent: NSEvent).

override func mouseEntered(theEvent: NSEvent) {
    // This does not work
    let data1 = theEvent.userData as [NSObject : AnyObject]
    let data2 = theEvent.userData as [String : NSView]
    let data3 = theEvent.userData as NSDictionary
}

My code is based on this Objective-C Sample Code provided by Apple. To quote line 372 of SuggestionsWindowController.m:

HighlightingView *view = [(NSDictionary*)[event userData] objectForKey: kTrackerKey];

So how can I read the event’s userData?

I have looked at this StackOverflow Q&A but it does not work.

enter image description here


Solution

  • If you want to read trackerData from the event, you have to get the user info from the tracking area

    if let userInfo = theEvent.trackingArea?.userInfo {
      let trackerData = userInfo["myTrackerKey"]! as! NSView
      // do something with the view
    }