'will quit' and 'should quit afer last window' are fighting

My single window AS app wites out it’s preferences when it ‘will quit’ :

on will quit theObject
	set sample_pref to (contents of button "sample_item" of box "preferences" of window "workout_buddy")
	tell user defaults
		set contents of default entry ("sample_pref") to sample_pref
	end tell 
end will quit

Which works fine, unless I try to quit the app with the close window button and the ‘should quit after last window’ action. If the app quits that way, an NSrecivererror is thrown. I’ve searched around can’t seem to find anyone else with this problem. Any way to make them work harmoniously (as it seems they should get along)? Or are there issues with mixing will quit and should quit actions?

just a last ditch bump to see if anyone knows the answer to my question…

Yeah, I think your window is being unloaded from memory, so references to its objects fail.

What I do with my scripts is use “on should close” to make the window invisible then return false so it doesn’t actually close. I can still reference its objects afterwards.

The only problem is that making them invisible probably won’t call the “should quit after last window” (I don’t use that handler myself). You’ll have to add a bit of code to see if it’s the last window visible when it’s being closed, and quit if that’s the case.

Here’s the idea:

on should close theObject
	if name of theObject is "preferences" then
		set visible of window "preferences" to false
		set prefWindowOpen to false
		-- add code to check if it's the last window and quit if that's the case
		return false
	end if
end should close

on will quit theObject
	updatePropertiesFromPrefs() -- copy items from text fields, etc. into variables
	set visible of window "preferences" to false -- if it isn't already
	writeDefaults() -- save those prefs!
end will quit