How to Get Properties of Custom NSView Inside Its Implementation

Hey Everybody, I’d like to understand the fundamental impossibility of a subclassed NSView to read its own properties, like frame or bounds.
The NSView’s description says that: <MYView @0x60000015a6d0: OSAID(4) ComponentInstance(0x810002)>

All I wanted is to read frame size of my view inside its implementation. I tried several approaches: declare a property, write a method. I’m clearly missing something of how AppleScript works. When I expect the frame message I get nothing but the error:

script MYView
  	property parent : class "NSView"
  	property NSColor : class "NSColor"
  	on initWithFrame:frame
  		continue initWithFrame:frame
 		return me
  	end initWithFrame:
 	on drawRect:dirtyRect
 		continue drawRect:dirtyRect
 		NSColor's brownColor()'s setFill()
 		current application's NSRectFill(dirtyRect)
 	end drawRect:
 	on mouseUp:theEvent
 		display dialog my frame's |description|() as text
 	end mouseUp:
end script

I can’t try it at the moment, but I’d guess that my is probably going to refer to the script/class, rather than an instance of it.

Thank you Shane for your quick reply. At this point, I wonder why it let me do setFrame for the instance at the same time, like: my setFrame:{…}

Actually, the problem is more likely the fact that you’re trying to call the description method on what is probably a record at that stage. Try something like this:

display dialog (current application's NSStringFromRect(my frame())) as text
1 Like

It works, as long as it does in drawRect

current application's NSRectFill(my |bounds|())

Anyway I’d like to know more how it all works. Except your book I see nothing on ApplescriptOBJC.

Thank you very much Shane!

I presume you mean subclassing in ASObjC. It was covered fairly extensively in my earlier book on using ASObjC in Xcode. That was discontinued for a few reasons, one of which is that AppleScript’s memory management can make using ASObjC like that problematic.

I didn’t know there was another book in addition to “Everyday AppleScriptObjC”. That’s sad it’s been discontinued.

There is a solution for somebody who don’t like messing with records and all that ()'s in ApplesScript.

set {origin:{x:x, y:y}, |size|:{width:width, height:height}} to (sender's frame()) as record

Unfortunately that fails in recent versions, where NSRects are returned as lists of lists ({{x, y}, {width, height}}) rather than records. Depending on what you’re doing, you need to either check the class of the result, or use functions to extract individual values.

1 Like