Become a MacRumors Supporter for $25/year with no ads, private forums, and more!
  • Did you order new AirTags? We've opened a dedicated AirTags forum.

Tejashree

macrumors newbie
Original poster
Feb 23, 2009
5
0
Hi,
I want to close a alert Window (NSAlert) after specific period of time if user
does not click on any of the buttons.
Is there a way to set up a NSTimer to close the Alert Panel after 10 secs.

I am doing following thing and its working. But I know this wrong way to do this.
..........................................
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle: @"OK"];
[alert setMessageText: @"Attention!!! This a critical Alert."];
[alert setAlertStyle: NSInformationalAlertStyle];

NSTimer *myTimer = [NSTimer timerWithTimeInterval: 5
target:self
selector: @selector(killWindow:)
userInfo:nil
repeats:NO];

[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSModalPanelRunLoopMode];

int choice = 0;
choice = [alert runModal];
if(choice != 0)
[myTimer invalidate];
..........................................
-(void) killWindow:(NSTimer *) theTimer
{
NSLog(@"killWindow");
[[alert window] close];
}
..........................................


Can anyone please suggest the best way to do this.

Thanks,
Tejashree.
 

HiRez

macrumors 603
Jan 6, 2004
6,000
2,005
Western US
Why do say you know it's wrong? You said it works, right? Only thing I can see is you set of for 5 seconds when you said you wanted 10.
 
Comment

mathcolo

macrumors 6502a
Sep 14, 2008
860
16
Boston
Yeah, if it's working for you then I wouldn't bother changing it. Despite that, that's how I'd do it; an NSTimer controlling NSAlert.

Sometimes you have to just let code be code :D
 
Comment

ruchi830

macrumors newbie
Jan 10, 2013
4
0
I used this same code, but when I try to close with a timer, the rest of my app freezes. Also, if I try to do NSApp.stopModal to stop running Modal, the app crashes. Any ideas on the correct way to do this?
 
Comment

gnasher729

macrumors P6
Nov 25, 2005
17,941
5,478
I'd try abortModal instead of stopModal, that's what the documentation says. And your memory management seems dubious. [autorelease] should release the alert before the next round of the run loop, so by the time the timer fires, the alert should be gone. What does the static analyzer think of your code?
 
Comment
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.