progrium/darwinkit

Question about NSControl initWithFrame

Closed this issue · 5 comments

I was wondering why is the NSControl method initWithFrame: binded as InitWithFrame__asNSControl()? I think it would be easier on users if it was called InitWithFrame().

I updated to MacDriver 0.4.0 and now this method is gone.

Found it as InitWithFrame_AsNSControl.

I am not a fan of all these InitWithFrame_As methods. I would prefer a simple following the standard InitWithFrame() method.

I implemented my own InitWithFrame() method right under the InitWithFrame_AsNSControl() method and it worked 😃.

func (x gen_NSControl) InitWithFrame_AsNSControl(
	frameRect core.NSRect,
) NSControl {
	ret := C.NSControl_inst_InitWithFrame(
		unsafe.Pointer(x.Pointer()),
		*(*C.NSRect)(unsafe.Pointer(&frameRect)),
	)

	return NSControl_FromPointer(ret)
}

func (x gen_NSControl) InitWithFrame(frameRect core.NSRect) NSControl {
	return x.InitWithFrame_AsNSControl(frameRect)
}

This is my test program:

package main

import "github.com/progrium/macdriver/cocoa"
import "github.com/progrium/macdriver/objc"
import "github.com/progrium/macdriver/core"


func main() {

	app := cocoa.NSApp_WithDidLaunch(func(n objc.Object) {
		win := cocoa.NSWindow_New()
		win.SetTitle("NSSlider")

		/* NSSlider code */
		rect := core.NSMakeRect(10, 50, 70, 20)
		slider := cocoa.NSSlider_Alloc()
		slider.InitWithFrame(rect) // Way better looking
		win.ContentView().AddSubview(slider)
		
		win.MakeKeyAndOrderFront(nil)
	})

	app.SetActivationPolicy(cocoa.NSApplicationActivationPolicyRegular)
	app.ActivateIgnoringOtherApps(true)
	app.Run()
}

So can we have an InitWithFrame() method?

tmc commented

I agree but it's not super straightforward: the objc.Object interface expects Init() to return objc.Object which meants we'd need to treat Init() differently. That may be fine to do, I haven't thought it through, just highlighting a little nuance. Note that there's the semi-related - (instancetype)init NS_UNAVAILABLE; case we need to handle as well.

I am having difficulty trying to follow. I am pretty sure NSControl's InitWithFrame() probably calls NSObject's Init() method eventually, but how is this a problem? My code shows having a NSControl InitWithFrame() function can work. I admit I haven't tested every situation that might be encountered yet. I haven't tried adding the NSSlider instance to a collection object like NSDictionary or NSArray. But I am still confident that having a NSControl InitWithFrame() method would be a great idea.