UIAlertView警报-iOS开发


  1. UIAlertView* myAlert = [[UIAlertView alloc]  
  2.                     initWithTitle:@"sorry"   
  3.                     message:@"1234567890"   
  4.                     delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];  
  5.                     myAlert.delegate =    self;  
  6.                     [myAlert show];  
  7.                     //[myAlert release];//如果未在下面的委托中release的话记得要在这里release,否则内存泄漏了  
这里设置delegate有啥用出,加入我们仅仅是只要显示一个弹窗警告,而不采取其他动作我们可以安全用如下代码解决:
  1. [[[[UIAlertView alloc]  
  2.                 initWithTitle:@"sorry"   
  3.                 message:@"1234567890"   
  4.                 delegate:self   
  5.                 cancelButtonTitle:@"OK"   
  6.                 otherButtonTitles:nil, nil]  
  7.                 autorelease]  
  8.                 show];  

设置委托有啥作用呢?我们可以实现UIAlertView的一个委托方法,让后可以在这个方法里处理按下按钮后的动作,根据用户按下的哪个按钮来决定进行射门样的操作,比如按下OK按钮与按下Cancel按钮的后要进行的操作必然有可能不同:

  1. -(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{  
  2.     NSLog(@"Button %d pressed",buttonIndex);  
  3.     [alertView release];  
  4. }  
看到否?我们可以通过buttonIndex来判断用户按下了哪个按钮,然后来进行相应处理,同时我们还可以在这里面release,因为我们在上面的代码中可能不确定需要在哪里release,所以在按下按钮后release是不是最安全的呢?

相关内容