CocoaDev

Edit AllPages

I have a document based app, which opens a blank document when I start it.

Is there any way to make it open the last file saved on startup, rather than a new/blank file? It seems like that would be a commonly desired behavior, but I haven’t been able to find any way to do it. I did find “applicationOpenUntitledFile”, to control whether a new file is opened, but not a way to say open the last file saved.


Not too difficult. In your app delegate:

Corrected - I used code from an old project of mine and the newer method I use is better. :-) You could improve it by enumerating the list … that way if the ‘fileExistsAtPath:’ fails, you can keep going back to the previous document until you find one that still exists.


That worked great, thanks for the response.


Just note the “if user prefers” part. Not everybody wants this non-standard behavior. In fact, many prefer otherwise, which is probably a good reason to have it off by default, too. :-)

Few things updated for OS X 10.4, since openDocumentWithContentsOfFile:display: has been deprecated. Here’s a new version that seems to work. (Since it took me a little while to figure this part out, edit [[MainMenu.nib in IB, click on classes, add a class “MyAppDelegate,” instantiate it, click on Instances, control-drag between File’s Owner and myAppController, press Apple-2, and set choose delegate for this outlet connection. add the files to XCode, then add this code to MyAppDelegate.m.) I’m a novice, so please fix any errors if you find them!

-dan

This is a lot simpler, you don’t need to alloc the myURL, since it’s just pointing into the array. Also, you can use a simple for loop on an NSArray, XCode even makes one for you with tab completion.


Make sure AppController instance is in MainMenu.nib, not MyDocument.nib. I’ve just made this stupid mistake… – DmitryChestnykh

Also, here’s 10.5 version:


Isn’t this the wrong place for the code? Since now, if the user closes the document and wants to open a new one, the existing document is opened again. I think this code should go into willFinishLaunching, or am I wrong? –wackazong