Objective C - Asking to save before you quit
There are better ways to do this within the Cocoa framework, such as by using NSDocument
and its ilk. However, it is possible to do what you want to do.
You first want to return NSTerminateLater
in applicationShouldTerminate:
:
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if (theDATA.issavedsomewhere) {
return NSTerminateLater;
}
return NSTerminateNow;
}
Then, you handler should ultimately call [NSApp replyToApplicationShouldTerminate:YES]
when it is done:
NSSavePanel *panel = [NSSavePanel savePanel];
// NSInteger result;
[panel setAllowedFileTypes:@[@"txt"]];
[panel beginWithCompletionHandler:^(NSInteger result){
//OK button pushed
if (result == NSFileHandlingPanelOKButton) {
// Close panel before handling errors
[panel orderOut:self];
// Do what you need to do with the selected path
NSString *selpath = [[panel URL] path];
NSError *error;
BOOL didOK = [[theDATA.textvieww string]writeToFile:selpath atomically:NO encoding:NSUTF8StringEncoding error:&error];
if(!didOK){
//error while saving
NSLog(@"Couldn't Save!!! -> %@", [error localizedFailureReason]);
}else{
//success!
theDATA.issavedsomewhere=YES;
theDATA.filepath=selpath;
theDATA.filename=[[[panel URL] path] lastPathComponent];
}
}/*Button other than the OK button was pushed*/
else{
}
[NSApp replyToApplicationShouldTerminate:YES];
}];