Re: NSAlert boxes ...


Jon Gotow
 

You're making this far more complicated than it is (talking about running the alert asynchronously, etc).

NSModalResponse choice = [alert runModal];

will run the alert synchronously. Note that it returns a result from this method call, meaning that the call blocks by running its own modal event loop in runModal and only returns after the user has clicked on a button. That means that your autorelease is fine - the scope of this alert is just within the current function, so it'll get cleaned up at the end of the current runloop invocation. That said, you can also just release it manually after you call runModal, like this:

NSAlert *alert = [[NSAlert alloc] init];

alert.messageText = @"Some message or other”;
[alert addButtonWithTitle:@"Create category"];
[alert addButtonWithTitle:@"Cancel"];

NSModalResponse choice = [alert runModal];

[alert release];

If you were to use [NSAlert beginSheetModalForWindow:completionHandler:], then you'd have to worry about lifecycle of the alert extending beyond the current function context.

- Jon

On Feb 16, 2020, at 6:17 AM, Peter Hudson via Groups.Io <Peter.hudson@...> wrote:

Hi There

I see from the docs that when you create an NSAlert that you should dispose of it yourself.
My code for creating a simple alert and using it looks like this :-


NSAlert *alert = [[[NSAlert alloc] init] autorelease];
alert.messageText = @:Some message or other”;
[alert addButtonWithTitle:@"Create category"];
[alert addButtonWithTitle:@"Cancel"];

NSModalResponse choice = [alert runModal];

Etc …..

Is the use of an autorelease here O.K. ?

It certainly seems to work …..



Peter

Join {cocoa@apple-dev.groups.io to automatically receive all group messages.