10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Objective-C] UIAlertViewを同期処理する

Posted at

JavaScriptなどではアラートは同期処理になりますが、Objective-Cでは非同期処理になります。(デリゲートで処理するため)

ただ、場合によっては同期的に処理をしたい場合があるので、どうするかのメモです。

※ちなみに、viewDidLoad内でやっちゃうとちゃんとviewの描画処理が終わらなくなるのでうまく動きません。慣れてる人はそんなミスしないんだと思いますが、さっと処理を書いたらうまく動かなくてハマりました。

##NSRunLoopを使って同期処理にする

@property (assign, nonatomic) BOOL finished;
- (void)anyMethod
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"TItle"
message:@"message"
delegate:self
cancelButtonTitle:@"cancel"
otherButtonTitles:@"other", nil];

	[alert show];

	self.finished = NO;

	while(!self.finished) {
		[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
	}

	NSLog(@"OK!");
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(UIInteger)buttonIndex
{
	self.finished = YES;
}
10
11
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?