• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 686
  • Last Modified:

Retaining an NSWindow size and state - looking for an elegant way to do this

I have a controller class which spawns a window when a certain condition occurs. This window can be closed by the user, moved around or resized.

Ideally, when this condition occurs, I'd like the window to re-open in the same spot the user closed it last time.

Looking for an elegant way to do this. Pointers (or references) will be most welcome.
  • 3
1 Solution
I'm not sure I understand. You want to know how to move? setFrame, I think. The parameter is NSRect.

ronenmagid1Author Commented:
No, I can do that myself.

This is why I said "elegant". I thought there might be some Cocoa class that takes the snapshot of the windows location and/or if it's currently miniaturized and saves it into a pfile or something.
I attached an action method as an example.
Full example is here:

- (IBAction)move: (id) sender
    // The button frame.
    NSRect senderFrame = [sender frame];
    //The view bounds. The button belongs to this view.
    NSRect superBounds = [[sender superview] bounds];
    // Calculate new position within the view bounds.
    senderFrame.origin.x = (superBounds.size.width -
                            senderFrame.size.width) * drand48();
    senderFrame.origin.y = (superBounds.size.height -
                            senderFrame.size.height) * drand48();
    // Move the button.
    //[sender setFrame: senderFrame];
    [[sender animator] setFrame: senderFrame];

Open in new window

Do you need to store the rectangle somewhere and then read it and restore the view position?
Use NSUserDefaults. An example attached.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[NSDate date] forKey:@"Date and Time"];
    [defaults synchronize];
    NSDate *today = [defaults objectForKey:@"Date and Time"];
    NSLog(@"Saved data: %@", today);
    [pool drain];
    return 0;

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now