Saving a Window’s Position into the User’s Defaults

A window can store its placement in the user defaults system, so that it appears in the same location the next time the user starts the application. The saveFrameUsingName: method stores the frame rectangle, and setFrameUsingName: sets it from the value in user defaults. You can also use the setFrameAutosaveName: method to have a window save the frame rectangle any time it changes. However, for the correct frame to be saved, you must ensure that the window controller for the window in question doesn’t cascade the windows under its charge. You accomplish this task by sending setShouldCascadeWindows:NO to the controller, as shown in Listing 1.

Listing 1  Saving a window’s frame automatically

NSWindow *window = // the window in question
[[window windowController] setShouldCascadeWindows:NO];      // Tell the controller to not cascade its windows.
[window setFrameAutosaveName:[window representedFilename]];  // Specify the autosave name for the window.

To expunge a frame rectangle from the defaults system, use the class method removeFrameUsingName:.